PowerShell: How to Use Select-String with Exact Match


You can use the following basic syntax in PowerShell to use the Select-String cmdlet to search for a string that exactly matches a pattern:

Select-String "\bWest\b" -Path "c:\users\bobbi\data1\conferences.txt"

This particular example returns all lines from the file named conferences.txt that contain the exact string “West” anywhere in the line.

Note that we use \b before and after the string we’re interested in to indicate word boundaries.

This allows us to return only the lines that contain the exact string “West” and no variation such as “Midwest” or “Western” or something similar.

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

Example: How to Use Select-String with Exact Match in PowerShell

Suppose that we have a file located at the following path:

  • c:\users\bobbi\data1\conferences.txt

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

The file contains six total lines that provide information about the conference that various basketball teams belong to in the NBA.

Suppose that we would like to return all of the lines that contain the exact string “West” anywhere in the line.

Suppose that we attempt to use the following syntax to do so:

Select-String "West" -Path "c:\users\bobbi\data1\conferences.txt" 

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

This returns each line that contains “West”, regardless of an exact match.

For example, we can see that lines that contain either “West” or “Western” are both returned.

In order to search for an exact match, we must use the following syntax instead:

Select-String "\bWest\b" -Path "c:\users\bobbi\data1\conferences.txt" 

PowerShell Select-String exact match

This returns only line number 4 in the file, which is the only line that contains the exact string “West” and not some variation of the word.

Related Tutorials

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

PowerShell: Use Select-String to Search for Multiple Patterns
PowerShell: Use Select-String to Recursively Search for Strings
PowerShell: A Simple Formula for “Not Contains”

Leave a Reply