0
0
PowershellHow-ToBeginner · 3 min read

How to Use Select-String in PowerShell: Simple Guide

Use Select-String in PowerShell to search for text patterns in files or strings. It works like the 'find' command, returning matching lines with context. You specify the pattern with -Pattern and the target file or input with -Path or pipeline input.
📐

Syntax

The basic syntax of Select-String includes specifying the pattern to search and the input source. You can search files or strings.

  • -Pattern: The text or regex pattern to find.
  • -Path: The file(s) to search inside.
  • -InputObject: Use this to search strings passed through the pipeline.
  • -CaseSensitive: Optional flag to make search case-sensitive.
  • -AllMatches: Returns all matches in each line, not just the first.
powershell
Select-String -Pattern <string> -Path <string[]> [-CaseSensitive] [-AllMatches] [-SimpleMatch]
💻

Example

This example searches for the word 'error' in a file named 'log.txt' and shows the matching lines with their line numbers.

powershell
Select-String -Pattern "error" -Path "log.txt"
Output
log.txt:3:Error found in the system log.txt:15:Unexpected error occurred
⚠️

Common Pitfalls

One common mistake is forgetting that Select-String uses regular expressions by default, so special characters in the pattern need escaping or use -SimpleMatch for plain text search.

Another pitfall is not specifying the correct file path or using the wrong input type, which results in no matches.

powershell
## Wrong: special characters treated as regex
Select-String -Pattern ".*error.*" -Path "log.txt"

## Right: use -SimpleMatch for plain text
Select-String -Pattern ".*error.*" -Path "log.txt" -SimpleMatch
📊

Quick Reference

ParameterDescription
-PatternText or regex pattern to search for
-PathFile or files to search inside
-InputObjectString input from pipeline to search
-CaseSensitiveMake search case-sensitive
-AllMatchesReturn all matches per line
-SimpleMatchTreat pattern as plain text, not regex

Key Takeaways

Use Select-String with -Pattern and -Path to search text in files.
Remember Select-String uses regex by default; use -SimpleMatch for plain text.
You can pipe strings into Select-String using -InputObject or pipeline input.
Use -CaseSensitive to control case matching.
Check file paths carefully to avoid no matches.