PowerShell: Use Select-String and Exclude Specific Pattern


You can use the Select-String cmdlet in PowerShell to find specific text in strings and files.

Often you may want to use the Select-String cmdlet to select all lines in a file that do not contain a specific pattern.

You can use the following methods to do so:

Method 1: Use Select-String and Exclude One Specific Pattern

Get-Content employees.txt | Select-String -pattern $my_pattern -NotMatch

This particular example will retrieve all lines from the file named employees.txt that do not contain the pattern specified in the $my_pattern variable.

Method 2: Use Select-String and Exclude Multiple Specific Patterns

Get-Content employees.txt | Select-String -pattern $my_patterns -NotMatch

This particular example will retrieve all lines from the file named employees.txt that do not contain any of the patterns specified in the $my_patterns array.

The following example shows how to use each of these methods in practice.

Example 1: Use Select-String and Exclude One Specific Pattern

Suppose we have a file named employees.txt in our current directory that contains the ID values for various employees at some company.

We can use the Get-Content cmdlet to view all of the lines from this file:

Suppose that we would like to retrieve only the lines in the file that do not contain the pattern “A00” somewhere in the employee ID value.

We can use the following syntax to do so:

$my_pattern = "A00"
Get-Content employees.txt | Select-String -pattern $my_pattern -NotMatch

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

PowerShell Select-String exclude pattern

Notice that this returns only the lines from the file that do not contain the pattern “A00” somewhere in the line.

Example 2: Use Select-String and Exclude Multiple Specific Patterns

Suppose that we would like to only retrieve the lines in the employees.txt file that do not contain any of the following patterns somewhere in the employee ID value:

  • A00
  • B14
  • C00

We can use the following syntax to do so:

$my_patterns = @("A00", "B14", "C00")
Get-Content employees.txt | Select-String -pattern $my_patterns -NotMatch

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

PowerShell Select-String exclude multiple patterns

Notice that this returns only the lines from the file that do not contain one of the three patterns that we specified.

Note: You can find the complete documentation for the Select-String cmdlet in PowerShell here.

Related Tutorials

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

PowerShell: Use Select-String to Recursively Search for Strings
PowerShell: Use Select-String to Search for Multiple Patterns
PowerShell: Use Select-String with Exact Match
PowerShell: Use Select-String and Output Only Matching Text

Leave a Reply