24/7/365 Support

Filter Items in a List or Windows PowerShell Command Output

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.

Help Category:

Get Windows Dedicated Server

Only reading will not help you, you have to practice it! So get it now.

Processor RAM Storage Server Detail
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 128 GB (SSD SATA) Configure Server
Intel Atom C2750 2.4 GHz 8c/8t 8 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Xeon E3-1230 v2 3.3 GHz 4c/8t 16 GB DDR3 1× 256 GB (SSD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 250 GB (SSD SATA) Configure Server

What Our Clients Say