How to Search Files with Select-String in PowerShell

Search beam highlighting matching lines across application logs and configuration files

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

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 failed

How the Code Works

A process flow showing Select-String receiving one or more text-file paths and a search pattern, scanning each file, deciding whether lines match, and returning matching results with the file path, line number, and line text.
Select-String scans specified text files, applies a literal or regular-expression pattern, and returns details for each matching line.

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:

  • $_ .LineNumber identifies the matching line. Without the space, the property is written as $_.LineNumber.
  • $_.Line contains the complete line from the file.
  • .Trim() removes extra spaces at the beginning and end of the line.
  • The -f operator 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 either Environment or Port.
  • \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-ChildItem to inspect files before searching.
  • Forgetting wildcards: A path such as logs refers to a directory, not all files inside it. Use a pattern such as logs\*.log when searching log files.
  • Expecting exact case matching: Searches are case-insensitive by default. If capitalization matters, add the -CaseSensitive parameter.
  • Confusing plain text with a regular expression: Characters such as ., *, +, and ? have special meanings in regular expressions. Use -SimpleMatch when 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 WARN and ERROR.
  • 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-String searches one or more text files for a string or regular-expression pattern.
  • Use -Path to identify files and wildcards such as *.log to search multiple files.
  • Search results provide useful properties including Path, LineNumber, and Line.
  • Use regular expressions such as WARN|ERROR when one search should match multiple patterns.
  • Use -SimpleMatch when the search text should be treated literally rather than as a regular expression.

Leave a Comment

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

Scroll to Top
Ad
Ad
Ad