PowerShell: How to Use Regex with -notmatch


Often you may want to use PowerShell to find all lines in a particular file that do not match a specific pattern.

You can use the following basic syntax with the -notmatch operator to do so:

Get-Content employees.txt | Where {$_ -notmatch 'A\d\d\d'}

This particular example will return all lines from the text file named employees.txt that do not contain a string with the letter ‘A’ followed by three numeric characters.

Note that we used the Regex pattern \d to match numbers between 0 and 9.

Note that you can use any Regex pattern you would like in the quotes following the -notmatch operator to search for specific patterns.

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

Example: How to Use Regex with -notmatch in PowerShell

Suppose we have a file named employees.txt that contains the ID numbers for various employees at some company.

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

Suppose that we would like to return all lines in the file that do not contain a pattern that matches the letter ‘A’ followed by three numeric characters.

We can use the following syntax to do so:

Get-Content employees.txt | Where {$_ -notmatch 'A\d\d\d'}

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

PowerShell regex not match

Notice that this returns all lines in the file that do not contain the pattern that we specified.

Feel free to use any Regex pattern that you’d like following the -notmatch operator to search for any specific pattern.

Note: You can find the complete documentation for the -notmatch operator in PowerShell here.

Related Tutorials

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

PowerShell: How to Use Regex in Switch Statement
PowerShell: How to Use Regex to Capture All Matches
PowerShell: How to Split String Based on Regex Pattern

Leave a Reply