How do I use PowerShell Where-Object?

PowerShell Basics

May 31, 2020

quote Discuss this Article

PowerShell Where-Object is a cmdlet used to filter objects on the pipeline. You can pass a collection of objects to the cmdlet and then provide a filter to select only the objects that you wish to return. There are two common parameter sets for Where-Object. The first takes advantage of the various parameters on Where-Object. The second allows you to use a script block to compose more advanced queries.

Let’s take a look at the first type of filtering. We will filter the processes on the machine based on name.

Get-Process | Where-Object Name -eq 'Notepad'

The above command line will select the processes where the name is Notepad. When deciding how to filter objects returned from a particular cmdlet, you can use Get-Member to see the properties available on the object.

To create more complex queries, you can use a script block. The following will achieve the same result as the previous object.

Get-Process | Where-Object { $_.Name -eq 'notepad' }

The braces denote the beginning and end of a script block. It is similar to a function. This Where-Object script block is called for each process that is returned from Get-Process. The $_ variable is used to denote the current object in the array of objects returned.