How to Search for Text Inside Files with PowerShell

📜Part of the PowerShell Complete Guide, every PowerShell post on this site, grouped by the job you are doing.
The short answer

Select-String is the PowerShell equivalent of grep. Pipe files into it, or point it at a path with -Path.

Windows search is not much use for finding a connection string buried in a config file, or which of forty log files contains the error you care about. Select-String is, and it reports the line number so you can go straight there.

Search a Folder of Files

PowerShell
Get-ChildItem -Path "D:\Logs" -Recurse -Filter *.log |
    Select-String -Pattern "ERROR" |
    Select-Object Filename, LineNumber, Line |
    Format-Table -AutoSize
Get-ChildItem piped to Select-String finding ERROR lines in D:\Logs, shown as a table of file name, line number and line

Real output from a folder of test logs:

PowerShell piping the log files in D:\Logs into Select-String for ERROR, with a table of Filename, LineNumber and Line for the three matches

Just Tell Me Which Files

When you only want the filenames rather than every matching line, -List stops at the first match per file, which is also much faster across a large tree:

PowerShell
Select-String -Path "D:\Logs\*.log" -Pattern "timeout" -List | Select-Object -ExpandProperty Path
Select-String -List returning only the paths of the log files that contain timeout

Useful Switches

PowerShell
# case sensitive (Select-String is case INsensitive by default)
Select-String -Path .\app.config -Pattern "Password" -CaseSensitive

# plain text rather than a regular expression
Select-String -Path .\notes.txt -Pattern "3.5.1" -SimpleMatch

# show two lines either side of the match
Select-String -Path .\app.log -Pattern "Exception" -Context 2,2

The switch worth remembering is -SimpleMatch. The pattern is a regular expression by default, so searching for something like an IP address or a version number will not do what you expect until you either escape the dots or pass -SimpleMatch.

Pattern not matching? Paste the pattern and a line it should have found into Claude and ask what the regular expression is doing. It is usually one unescaped character.

Related


If SQL Server is part of your day job, my current work lives over at sqldba.blog: production DBA scripts, an error library and the SSMS guide.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *