0
0
PowerShellscripting~5 mins

Regex with Select-String in PowerShell

Choose your learning style9 modes available
Introduction
Use regex with Select-String to find text patterns quickly in files or output. It helps you search for words or patterns without reading everything.
You want to find all lines containing a phone number in a text file.
You need to check if a log file has error messages matching a pattern.
You want to search for email addresses inside a folder of documents.
You want to filter command output to show only lines with dates.
You want to find words starting with a specific letter in a list.
Syntax
PowerShell
Select-String -Path <file_path> -Pattern <regex_pattern>
Use -Path to specify the file or files to search.
The -Pattern parameter accepts regular expressions to match complex text.
Examples
Finds all lines containing the word 'error' in log.txt.
PowerShell
Select-String -Path "log.txt" -Pattern "error"
Finds lines with a pattern like 123-45-6789 (a simple SSN format).
PowerShell
Select-String -Path "data.txt" -Pattern "\d{3}-\d{2}-\d{4}"
Searches lines starting with 'Chapter' in notes.txt.
PowerShell
Get-Content notes.txt | Select-String -Pattern "^Chapter"
Sample Program
This script outputs four fruit names and uses Select-String to find lines starting with 'a'.
PowerShell
Write-Output "apple`nbanana`napricot`nblueberry" | Select-String -Pattern "^a"
OutputSuccess
Important Notes
Regex patterns are case-insensitive by default in Select-String. Use -CaseSensitive to change this.
You can search multiple files by using wildcards in -Path, like '*.txt'.
Select-String outputs match info including the line text and line number.
Summary
Select-String helps find text patterns in files or output using regex.
Use -Pattern to specify the regex and -Path for files to search.
It is useful for quick searches without opening files manually.