Tuesday, July 7, 2015

PowerShell Grep Equivalent

Select-String is a cmdlet in PowerShell that allows searching of files, piped input, objects, etc for a pattern (by default a regular expression). Some examples:

PS C:\>events = get-eventlog -logname application -newest 100
PS C:\>$events | select-string -inputobject {$_.message} -pattern "failed"

This searches for the string "failed" among the last 100 events in the Application log in Event Viewer.

PS C:\>get-childitem c:\windows\system32\*.txt -recurse | select-string -pattern "Microsoft" -casesensitive

This searches all .txt files in the \system32 folder for the case-sensitive string "Microsoft".

PS C:\>get-childitem c:\ -include *.txt -recursive | select-string -pattern "password"

Similar but searches for all .txt files on the C:\ drive.

PS C:\>select-string -path process.txt -pattern idle, svchost -notmatch

This searches the process.txt file for lines that DO NOT include "idle" or "svchost".


More on Select-String at Technet.