PowerShell grep files

PowerShell has functionality somewhat like grep. Use regular expressions to find matching text in files and piped text using Select-String.

Grep files:

Get-ChildItem -Path . -Filter *.txt -Recurse | Select-String -Pattern 'foo'

Grep specific file:

Select-String -Path CMakeLists.txt -Pattern 'project'

Grep piped text:

cat CMakeLists.txt | Select-String -Pattern 'project'

Grep piped text with regex:

cat CMakeLists.txt | Select-String -Pattern 'project\s*\('

Make a grep() function in PowerShell by saving the following to a file “grep.ps1”. To use this function in PowerShell command line, source the file with . grep.ps1 and then use the function from the PowerShell command line like grep pattern filename. One could make this function fancier to be more grep-like.

function grep($pattern, $path) {
    Select-String -Path $path -Pattern $pattern