Problem
You want to filter the items in a list or command output.
Solution
Use the WhereObject cmdlet (which has the standard aliases, where and ?) to select items in a list (or command output) that match a condition you provide.
To list all running processes that have "search" in their name, use the like operator to compare against the process’s Name property:
GetProcess | WhereObject { $_.Name like "*Search*" }
To list all directories in the current location, test the PsIsContainer property:
GetChildItem | WhereObject { $_.PsIsContainer }
To list all stopped services, use the eq operator to compare against the service’s Status property:
GetService | WhereObject { $_.Status eq "Stopped" }
Discussion
For each item in its input (which is the output of the previous command), the WhereObject cmdlet evaluates that input against the script block that you specify. If the script block returns True, then the WhereObject cmdlet passes the object along. Otherwise, it does not. Ascript block is a series of PowerShell commands enclosed by the { and } characters. You can write any PowerShell commands inside the script block. In the script block, the $_ variable represents the current input object. For each item in the incoming set of objects, PowerShell assigns that item to the $_ variable, and then runs your script block. In the preceding examples, this incoming object represents the process, file, or service that the previous cmdlet generated.
This script block can contain a great deal of functionality, if desired. It can combine multiple tests, comparisons, and much more.
For simple filtering, the syntax of the WhereObject cmdlet may sometimes seem overbearing.
For complex filtering (for example, the type you would normally rely on a mouse to do with files in an Explorer window), writing the script block to express your intent may be difficult or even infeasible.
For more information about the WhereObject cmdlet, type GetHelp WhereObject.