PowerShell: How to Use Where-Object in List

Often you may want to use the Where-Object cmdlet in PowerShell to filter an object to only contain items that belong in a specific list.

You can use the following basic syntax to do so:

Import-Csv $my_file | Where-Object { $_.team -in $specific_teams}

This particular example will import the CSV file located at the path specified by $my_file, then filter the file to only display rows where the value in the team column is in the list specified by $specific_teams.

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

Example: How to Use Where-Object in List in PowerShell

Suppose we have a CSV file saved at the following location:

  • c:\users\bobbi\nba_data.csv

Suppose we use the Import-Csv cmdlet to view the contents of this entire file:

The file contains three columns that show the team, points and assists for various basketball players.

Suppose that we would like to only import the rows where the string in the team column belongs in the following list:

  • Mavs
  • Hawks
  • Kings
  • Rockets

We can use the following syntax to do so:

$my_file = "c:\users\bobbi\nba_data.csv"
$specific_teams = @("Mavs", "Hawks", "Kings", "Rockets")

Import-Csv $my_file | Where-Object { $_.team -in $specific_teams}

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

PowerShell Where-Object in list example

Notice that only the rows that contain one of the team names specified in $specific_teams are included in the output.

Note: To exclude rows that contain specific team names, simply replace the -in operator with the -notin operator instead.

Related Tutorials

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

PowerShell: How to Return Multiple Values from Function
PowerShell: How to Find Duplicate Values in Array
PowerShell: How to Get Last Item in Array

Leave a Reply