Skip to main content

How to Search Text in a File in PowerShell with Select-String

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

To find the lines of a log that mention an error, Linux and macOS have grep. PowerShell has Select-String: it searches a file or piped text and returns each matching line, with the file name and line number. This guide finds the errors in a small log file, with real output from PowerShell 7.6.10.

Syntax​

Syntax
Select-String -Path <file> -Pattern "<text>"
<command> | Select-String "<text>"
PartWhat it means
-Path <file>The file to search. Wildcards such as *.log search several
-Pattern "<text>"What to look for. It's a regular expression, so plain words work as they are
| Select-StringSearches text that another command sends down the pipeline

The reference: "The Select-String cmdlet uses regular expression matching to search for text patterns in input strings and files."

Prerequisites​

  • PowerShell 7. This guide uses PowerShell 7.6.10.

Step 1: Create a Log File​

Save this as app.log:

app.log
INFO Started
ERROR Disk is full
INFO Saved the report
ERROR Network is down

Step 2: Find the Errors​

PowerShell
Select-String -Path app.log -Pattern "ERROR"
Output
app.log:2:ERROR Disk is full
app.log:4:ERROR Network is down

PowerShell running Select-String -Path app.log -Pattern ERROR, printing app.log:2 Disk is full and app.log:4 Network is down.

Each match shows the file, the line number and the line: the errors are on lines 2 and 4.

Common Mistakes​

MistakeWhat happensDo this instead
Expecting the search to match case-Pattern "error" found the same two ERROR linesAdd -CaseSensitive: with it, error matched nothing
Searching for a character with special meaning, such as (The pattern is a regular expression: -Pattern "(" failed with The string ( is not a valid regular expressionAdd -SimpleMatch to search for the text as it is: it found the line with (

Troubleshooting​

SymptomLikely causeFix
Lines appear without a file name and numberThe text came down the pipeline, not from a file: Get-Content app.log | Select-String "ERROR" printed only the two linesUse -Path when you want the line numbers

FAQ​

How do I count the matches?​

Wrap the command and read Count: (Select-String -Path app.log -Pattern "ERROR").Count printed 2.

Is it case-sensitive by default?​

No. The reference, for -CaseSensitive: "Indicates that the cmdlet matches are case-sensitive. By default, matches aren't case-sensitive."

Conclusion​

Select-String -Path app.log -Pattern "ERROR" found the two error lines and named their line numbers, 2 and 4. Add -CaseSensitive to match case exactly.

Additional Resources​

  • Select-String — every parameter, including -SimpleMatch and -Context.