PowerShell: How to Filter a List of Strings


You can use the following methods in PowerShell to filter a list of strings:

Method 1: Filter a List of Strings Using One Pattern

$my_files | where { $_ -match 'teams' }

This particular example will filter the list of strings stored in $my_files to only display the ones that match the pattern ‘teams’ somewhere in the string.

Method 2: Filter a List of Strings Using Multiple Patterns

$my_files | where { $_ -match 'teams|sales' }

This particular example will filter the list of strings stored in $my_files to only display the ones that match the pattern ‘teams’ or the pattern ‘sales’ somewhere in the string.

The following examples show how to use each of these methods in practice.

Example: How to Filter a List of Strings in PowerShell

Suppose we use the following syntax to retrieve each of the filenames in our current directory and store these names in a variable named $my_files:

$my_files = Get-ChildItem | Select -Expand Name

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

We can see that the $my_files variable contains the following filenames:

  • nba_data.csv
  • sales_data.csv
  • teams1.txt
  • teams2.txt
  • teams3.txt

Suppose that we would like to filter this list to only display the filenames that match the pattern “teams” in the filename.

We can use the following syntax to do so:

$my_files | where { $_ -match 'teams' }

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

PowerShell filter list of strings

Notice that this returns only the files that contain the pattern “teams” in the filename.

We could also use the following syntax to filter the filenames to only display the ones that contain “teams” or “sales” in the filename:

$my_files | where { $_ -match 'teams|sales' }

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

PowerShell filter list of strings based on multiple patterns

Notice that this returns only the files that contain the pattern “teams” or “sales” in the filename.

Note: The | operator is used for “OR” logic. Feel free to use this operator as many times as you’d like to filter for even more patterns.

Related Tutorials

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

PowerShell: How to Replace Multiple Strings in File
PowerShell: How to Replace Special Characters in String
PowerShell: How to Replace Text in String

Leave a Reply