PowerShell: Use Import-Csv Where Row Contains String


Often you may want to use the Import-Csv cmdlet in PowerShell to only import rows from a CSV file that contain a specific string.

You can use the following methods to do so:

Method 1: Import Rows that Contain Specific String

Import-Csv $my_file | where {$_.team -like '*ets*'}

This particular example imports only the rows from the CSV file specified at the path in the $my_file where the team column contains “ets” somewhere in the string.

Method 2: Import Rows that Contain One of Several Specific Strings

$my_teams = @('Mavs', 'Lakers', 'Hawks', 'Spurs')
Import-Csv $my_file | where {$my_teams -contains $_.team}

This particular example imports only the rows from the CSV file specified at the path in the $my_file where the team column contains one of the four strings specified in the $my_teams array.

The following examples show how to use each method in practice.

Example 1: Import Rows that Contain Specific String in PowerShell

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

  • c:\users\bobbi\nba_data.csv

We can use the Get-Content cmdlet to view the content of this file:

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

Suppose that we would like to only import the rows from the CSV file where the team column contains “ets” in the name.

We can use the following syntax to do so:

$my_file = 'c:\users\bobbi\nba_data.csv'
Import-Csv $my_file | where {$_.team -like '*ets*'}

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

PowerShell Import-Csv where contains

Notice that we’re able to successfully import only the rows from the file that contain “ets” somewhere in the team name.

Example 2: Import Rows that Contain One of Several Specific Strings in PowerShell

Once again suppose we have a CSV file saved in the following location:

  • c:\users\bobbi\nba_data.csv

We can use the Get-Content cmdlet to view the content of this file:

Suppose that we would like to only import the rows from the CSV file where the team column contains one of the following strings:

  • Mavs
  • Lakers
  • Hawks
  • Spurs

We can use the following syntax to do so:

$my_file = 'c:\users\bobbi\nba_data.csv'
$my_teams = @('Mavs', 'Lakers', 'Hawks', 'Spurs')
Import-Csv $my_file | where {$my_teams -contains $_.team} 

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

PowerShell Import-Csv where row contains one of several strings

Notice that we’re able to successfully import only the rows from the file that contain one of the four team names that we specified.

Related Tutorials

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

PowerShell: How to Use Import-Csv and Extract Specific Columns
PowerShell: How to Use Import-Csv with No Headers
PowerShell: How to Use Import-Csv and Foreach

Leave a Reply