PowerShell: Use Select-String to Recursively Search for Strings


You can use the following basic syntax in PowerShell to use the Select-String cmdlet to recursively search for a specific string in multiple files:

Get-ChildItem -recurse | Select-String Spurs

This particular example returns the lines from each file in the current directory that contains the string “Spurs” somewhere in the line.

If you would like the output to be shown in a more readable format, you can use the following syntax:

Get-ChildItem -recurse | Select-String Spurs | select LineNumber, Line, Path

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

Example: Use Select-String to Recursively Search for Strings 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” anywhere in the line.

We can use the following syntax to do so:

Get-ChildItem -recurse | Select-String Spurs

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

PowerShell select string recursive

The output displays information about each line that contains “Spurs” anywhere in the line:

  • The file conferences.txt contains “Spurs” on line 2 of the file.
  • The file teams.txt contains “Spurs” on line 5 of the file.

The output also displays the entire line from each file.

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 | select LineNumber, Line, Path

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

PowerShell Select-String recursively search through files

The output displays the line number, the actual line, and the full path to the file for each line that contains “Spurs” in this folder.

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