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
- Count Rows in CSV Files
- Tail a Log File in PowerShell
- SQL Server: Search for a String in All Tables
- PowerShell Complete Guide
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.
Leave a Reply