Unix and Linux have had the incredibly powerful grep tool for decades but windows has always been lacking. PowerShell brings the functionality of grep with the Select-String cmdlet.
Use Select-String to Grep a Single File
To grep a simple text file is as easy as:
Select-String -Path "D:\script\Lorem-Ipsum.txt" -Pattern 'Tachytelic'
You can also use a wildcard:
Select-String -Path "D:\script\*.txt" -Pattern 'Tachytelic'
Grep Recursively with Get-Childitem
Unlike grep, Select-String does not have the ability to search recursively, but you can pipe output to it from Get-ChildItem, like this:
Get-ChildItem -Path "D:\Script\*.txt" -Recurse | Select-String -Pattern 'tachytelic'
Piping to Select-String
Just like grep, you can pipe to Select-String like this:
Get-Content "D:\Script\Lorem-Ipsum.txt" |Select-String "tachytelic"
If you want to make it more like Unix/Linux, add an alias to the Select-String cmdlet:
Set-Alias -Name grep -Value Select-String
Then you can simply pipe to Select-String like this:
cat "D:\Script\Lorem-Ipsum.txt" |grep "tachytelic"
Loop through results from Select-String
Here is an example that greps for a string and uses the results in a loop to determine if some action should be taken:
$pattern = "tachytelic"
$files = Select-String -Path "d:\script\*.txt" -Pattern $pattern
foreach ($file in $files) {
$filename=$file.Filename
$item = get-item $file.Path
"File '{0}' matches the pattern '{1}'" -f $item.FullName, $pattern
"It was last modified on {0}" -f $item.LastWriteTime
$response = Read-Host -Prompt "Set the archive bit on this file?"
If ($response -eq 'Y') {
$item.attributes="Archive"
}
}
Which produces output like this:

grepping in Powershell seems to be incredibly fast, I have not conducted any testing against the performance of GNU Grep, but I don’t think you will be disappointed by the performance.

[…] you found this post interesting, I’ve also written up some examples of how to grep using Windows Powershell […]