What You’ll Learn
In this lesson, you will learn how to use PowerShell’s Select-String cmdlet to find text in files. You will search application logs for error messages and search configuration files for important settings.
- Search one file with
Select-String. - Search several files by using a wildcard path.
- Use regular expressions to match flexible text patterns.
- Read useful information such as the file path, line number, and matching line.
The Concept
Select-String searches text files for a pattern. It is similar to the grep command found on many Unix-like systems, but it is designed for PowerShell.
The basic syntax is:
Select-String -Path "path\to\file.log" -Pattern "text to find"The -Path parameter specifies which file or files to search. The -Pattern parameter specifies the text or regular expression to find.
When a match is found, Select-String returns an object containing information about the match. This includes the file path, line number, and complete matching line. You can display only the parts you need by using the object’s properties, such as Path, LineNumber, and Line.
This is useful when investigating application logs, finding configuration values, or checking many files without opening each file manually. For structured XML configuration, text searching may not be enough; PowerShell Select-Xml and XPath is a useful next step.
Basic Example
The following example creates a small application log and searches it for lines containing ERROR. In a real project, the log would already exist, but creating one here makes the example easy to run.
$logPath = Join-Path $PWD "application.log"
@"
2025-03-01 09:00:00 INFO Application started
2025-03-01 09:02:14 ERROR Database connection failed
2025-03-01 09:02:20 WARN Retrying database connection
2025-03-01 09:02:25 INFO Database connection restored
"@ | Set-Content -Path $logPath
Select-String -Path $logPath -Pattern "ERROR" |
ForEach-Object {
"{0}: {1}" -f $_.LineNumber, $_.Line.Trim()
}Expected Output
2: 2025-03-01 09:02:14 ERROR Database connection failedHow the Code Works
The first line stores the path to the log file in $logPath. $PWD represents the current directory, and Join-Path combines that directory with the file name.
The here-string between @" and "@ contains several lines of log data. Set-Content writes those lines to the file so that the search has data to read.
This command performs the search:
Select-String -Path $logPath -Pattern "ERROR"The pattern is case-insensitive by default. Therefore, it normally finds ERROR, Error, and error. Each match becomes a result object.
The pipeline sends each result to ForEach-Object. Inside the script block, $_ means the current match object:
$_ .LineNumberidentifies the matching line. Without the space, the property is written as$_.LineNumber.$_.Linecontains the complete line from the file..Trim()removes extra spaces at the beginning and end of the line.- The
-foperator inserts those values into the output format.
You can also inspect the complete result object directly:
Select-String -Path $logPath -Pattern "ERROR"This displays information such as the file name, line number, and matching text. Formatting the result yourself is helpful when you want clean output for a report or script.
Another Example
You can search multiple files by using a wildcard in the path. This example creates two configuration files and finds settings for the application environment and port.
$configDirectory = Join-Path $PWD "config"
New-Item -Path $configDirectory -ItemType Directory -Force | Out-Null
@"
Environment = Production
Port = 8080
LogLevel = Information
"@ | Set-Content -Path (Join-Path $configDirectory "web.conf")
@"
Environment = Staging
Port = 8081
FeatureFlags = BetaSearch
"@ | Set-Content -Path (Join-Path $configDirectory "worker.conf")
$settingPattern = "^(Environment|Port)\s*="
Select-String -Path (Join-Path $configDirectory "*.conf") -Pattern $settingPattern |
ForEach-Object {
"{0}:{1}: {2}" -f $_.Path, $_.LineNumber, $_.Line.Trim()
}The wildcard *.conf tells PowerShell to search every file ending in .conf inside the configuration directory. The pattern is a regular expression:
^means the match must begin at the start of the line.(Environment|Port)matches eitherEnvironmentorPort.\s*matches zero or more whitespace characters.=requires the setting to contain an equals sign.
This pattern finds both Port=8080 and Port = 8080. It does not match a sentence that merely mentions one of those words later in the line.
Common Mistakes
- Searching the wrong path: Confirm that the file exists and that the path points to the intended directory. You can use
Get-ChildItemto inspect files before searching. - Forgetting wildcards: A path such as
logsrefers to a directory, not all files inside it. Use a pattern such aslogs\*.logwhen searching log files. - Expecting exact case matching: Searches are case-insensitive by default. If capitalization matters, add the
-CaseSensitiveparameter. - Confusing plain text with a regular expression: Characters such as
.,*,+, and?have special meanings in regular expressions. Use-SimpleMatchwhen you want to search for literal text instead of a regular expression. - Getting no results: No output usually means that no line matched the pattern. Check the spelling, file path, and whether the pattern is too specific.
Try It Yourself
Use the application.log file from the first example and search for warning messages instead of errors. Display the line number and the matching line, just as the example did.
Then try searching for the word connection. Notice that this returns more than one line because the word appears in both an error and an informational message.
Challenge
Create a log file named server.log with at least four lines. Include lines containing INFO, WARN, and ERROR.
Write a PowerShell command that:
- Searches the file for both
WARNandERROR. - Uses one regular-expression pattern.
- Displays the line number and matching line.
Solution
$serverLogPath = Join-Path $PWD "server.log"
@"
2025-03-01 10:00:00 INFO Server started
2025-03-01 10:05:12 WARN Disk space is getting low
2025-03-01 10:07:45 ERROR Unable to write backup file
2025-03-01 10:10:00 INFO Health check completed
"@ | Set-Content -Path $serverLogPath
Select-String -Path $serverLogPath -Pattern "WARN|ERROR" |
ForEach-Object {
"{0}: {1}" -f $_.LineNumber, $_.Line.Trim()
}The pattern WARN|ERROR uses the regular-expression alternation operator, represented by the vertical bar. It matches a line containing either WARN or ERROR. The pipeline then formats each matching result with its line number and text.
Key Takeaways
Select-Stringsearches one or more text files for a string or regular-expression pattern.- Use
-Pathto identify files and wildcards such as*.logto search multiple files. - Search results provide useful properties including
Path,LineNumber, andLine. - Use regular expressions such as
WARN|ERRORwhen one search should match multiple patterns. - Use
-SimpleMatchwhen the search text should be treated literally rather than as a regular expression.



