Filter Items in a List or Command Output

Recipe 2.1. Filter Items in a List or Command Output

1. Problem

You want to filter the items in a list or command output.

2. Solution

Use the Where-Object 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:

        Get-Process | Where-Object { $_.Name -like "*Search*" }

To list all directories in the current location, test the PsIsContainer property:

        Get-ChildItem | Where-Object { $_.PsIsContainer }

To list all stopped services, use the -eq operator to compare against the service’s Status property:

        Get-Service | Where-Object { $_.Status -eq "Stopped" }


3. Discussion

For each item in its input (which is the output of the previous command), the Where-Object cmdlet evaluates that input against the script block that you specify. If the script block returns True, then the Where-Object cmdlet passes the object along. Otherwise, it does not. A script 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 more information about script blocks, see Section 10.3, “Write a Script Block.” For more information about the type of comparisons available to you, see “Comparison Operators” in Appendix A.

For simple filtering, the syntax of the Where-Object cmdlet may sometimes seem overbearing. The following section, Section 2.2, “Program: Simplify Most Where-Object Filters,” shows a script that can make simple filtering (such as the previous examples) easier to work with.

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 maybe difficult or even infeasible. If this is the case Section 2.3, “Program: Interactively Filter Lists of Objects” shows a script that can make manual filtering easier to accomplish.

For more information about the Where-Object cmdlet, type Get-Help Where-Object.

Tags: , , , ,