PowerShell: Use Select-String and Output Only Matching Text


You can use the following basic syntax in PowerShell to use the Select-String cmdlet to search for lines that contain specific text and only output the matching text:

(Select-String ...-... $my_file).Matches.Value

This particular example looks for the pattern …-…, which matches any three characters followed by a dash followed by three more characters,.

It looks for this pattern in each line of the file specified at the path in the $my_file variable and returns only the matching text instead of the entire line.

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

Example: How to Use Select-String and Output Only Matching Text in PowerShell

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

  • c:\users\bobbi\employee_id.txt

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

The file contains six lines that provide information about the ID number for various employees at some company.

Notice that each employee ID has the same pattern:

  • Employee ID Pattern: Three letters followed by a dash followed by three letters

Suppose that we would like return the employee ID only from each line.

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

Select-String ...-... $my_file

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

This returns each line that contains the pattern …-… anywhere in the line.

To return only the employee ID from each line, we can instead use the following syntax:

(Select-String ...-... $my_file).Matches.Value

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

PowerShell Select-String output only match

Notice that only the employee ID’s are returned from each line instead of the entire line.

By using .Matches.Value we are able to return only the exact pattern that we searched for instead of the entire line that contained the pattern.

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 Search for Multiple Patterns
PowerShell: Use Select-String to Recursively Search for Strings
PowerShell: How to Use Select-String with Exact Match

Leave a Reply