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

Get-ChildItem -Path "D:\Logs" -Recurse -Filter *.log |
    Select-String -Pattern "ERROR" |
    Select-Object Filename, LineNumber, Line |
    Format-Table -AutoSize

Real output from a folder of test logs:

Filename  LineNumber Line
--------  ---------- ----
file1.log          2 ERROR something bad
file2.log          2 ERROR something bad
file2.log          4 ERROR something bad

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:

Select-String -Path "D:\Logs\*.log" -Pattern "timeout" -List | Select-Object -ExpandProperty Path

Useful Switches

# 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.

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 *

Looking for SQL Server?

This site started as a SQL Server blog in 2017 and the archive is still here. The new SQL Server writing, and all the scripts, moved to a site of their own.

sqldba.blogScripts, error library, wait types, SSMS
Browse by topic