PowerShell: How to Filter Array of Objects by Property


Often you may want to filter an array of objects based on a specific property in PowerShell.

You can use the following syntax to do so:

$players | Where-Object { $_.team -eq "Kings" }

This particular example filters the array named $players to only display the objects in the array where the team property is equal to “Kings.”

Note that you could also use the ? command as an alias for the Where-Object cmdlet for shorter code:

$players | ? { $_.team -eq "Kings" }

The following example shows how to use this syntax in practice.

Example: How to Filter Array of Objects by Property in PowerShell

First, we can use the following syntax to create an array of objects named $players that contains information about four different basketball players:

$players = @(
[pscustomobject]@{team="Mavs";points=40;assists=12},
[pscustomobject]@{team="Kings";points=22;assists=7},
[pscustomobject]@{team="Hawks";points=25;assists=11},
[pscustomobject]@{team="Celtics";points=13;assists=9})

The following screenshot shows how to use this syntax in practice:

Now suppose that we would like to filter the array to only display the objects where the value in the team property is equal to “Kings.”

We can use the following syntax to do so:

$players | Where-Object { $_.team -eq "Kings" }

The following screenshot shows how to use this syntax in practice:

PowerShell filter array of objects by property

Notice that this only returns the one object in the array where the team property is equal to “Kings.”

Note that you can also filter using numeric values if you’d like.

For example, you can use the following syntax to filter the array to only display objects where the value in the points column is less than 30:

$players | Where-Object { $_.points -lt 30 }

The following screenshot shows how to use this syntax in practice:

PowerShell filter array of objects based on numeric value of property

Notice that this only returns the objects in the array where the value in the points column is less than ( -lt ) 30.

Feel free to use similar syntax to filter the objects in the array using any numeric value that you’d like.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Compare Two Arrays
PowerShell: How to Create an Array with Initial Size
PowerShell: How to Create an Array of Arrays
PowerShell: How to Remove Duplicate Values from Array

Leave a Reply