Get-Method | My-Madness | 2012 PowerShell Scripting Games Beginner Event #2

The details of the event scenario and the design points for Beginner Event #2 of the 2012 PowerShell Scripting Games can be found on the Hey, Scripting Guys! Blog.

Listed below are my notes about the requirements and design points:

Find all services that are running and can be stopped. The command must work against remote computers. Use the simplest command that will work. You do not need to write a script. Return the results to the screen, not to a file. You may use aliases.

I started out by running Get-Service on my local computer:


I then ran Get-Help Get-Service -Full to verify that there weren't any parameters I could use to filter with in an attempt to filter as far to the left as possible which would make the command more efficient. I then piped Get-Service to Get-Member to determine what the available properties were. I determined that there's a property named CanStop along with another named Status. I can see one of the status's in the initial command I ran in the screenshot above is Running, that's one of the pieces to this puzzle.


If I was unsure of what cmdlet to filter with at this point, I could run Get-Help \*filter\* to help me locate the cmdlet. I can see Where-Object is in the results:


There wasn't a way to filter on the Get-Service cmdlet so that means that I'll need to pipe it to the Where-Object cmdlet. Viewing the full help on this cmdlet shows me an example that's similar to part of what I need. The only difference is it filters on Stopped services:


Throw a -and into the script block { } of that example and add another property (CanStop) to filter on. In the case of CanStop, there's no need to test it to see if it's is equal to true or false since a boolean defaults to true. Specifying the ComputerName parameter gives this command a way to be run against remote computers by specifying a remote computer name in place of localhost, an array of computer names in a comma delimited list, or by using (Get-Content C:\filename.txt) to pull the computer names from a text file. You could also pull the computer names from Active Directory by using the Get-ADComputer cmdlet, but that's outside the scope of this scenario.


1Get-Service -ComputerName localhost | Where-Object -FilterScript {$_.Status -eq 'Running' -and $_.CanStop}