PowerShell: Use Select-String to Search for Multiple Patterns


You can use the following basic syntax in PowerShell to use the Select-String cmdlet to search for multiple patterns in multiple files:

Get-ChildItem -recurse | Select-String Spurs, Mavs, Celtics

This particular example returns the lines from each file in the current directory that contain one of the following strings anywhere in the line:

  • Spurs
  • Mavs
  • Celtics

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

Example: Use Select-String to Search for Multiple Patterns in PowerShell

Suppose that our current directory is located at the following path:

  • c:\users\bobbi\data1

We can type Dir to view all of the files in this directory:

The directory contains five files that contain various information about basketball players.

Suppose that we would like return all of the lines in these files that contain the string “Spurs”, “Mavs” or “Celtics” anywhere in the line.

We can use the following syntax to do so:

Get-ChildItem -recurse | Select-String Spurs, Mavs, Celtics

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

PowerShell Select-String multiple patterns

The output displays information about each line that contains “Spurs”, “Mavs” or “Celtics” anywhere in the line.

For example, we can see:

  • The file conferences.txt contains “Mavs” on line 1 of the file.
  • The file conferences.txt contains “Spurs” on line 2 of the file.
  • The file conferences.txt contains “Celtics” on line 3 of the file.

And so on.

If we’d like, we can use the following syntax to produce the same output but in a more readable format:

Get-ChildItem -recurse |
Select-String Spurs, Mavs, Celtics |
select LineNumber, Line, Filename

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

The output displays the line number, the actual line, and the file name for each line that contains “Spurs”, “Mavs” or “Celtics” in this current directory.

Related Tutorials

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

PowerShell: How to List Files in Directory by Date
PowerShell: How to List All Files in Directory to Text File
PowerShell: How to Delete All Files with Specific Extension

Leave a Reply