Grepping in PowerShell

Grepping in PowerShell

One tool I really miss sometimes is grep, the command line tool for searching for text matches inside an arbitrary set of files. In the same way you might use "dir" to find a file inside a directory that matches a name pattern, or another outward-facing characteristic like file attribute, you can use grep to find any files containing matching text.

In this most recent episode of pining for grep, I was only interested in finding out if a particular namespace was being used anywhere in my code and didn't really care where. You could easily extend this code to report the file name when it finds a match.


[string]$SourceFolder = 'D:\MyCode\Source'

$SearchTerms = @( 'using System.' )

Get-ChildItem -Path $SourceFolder -Filter *.cs -Recurse | % {

    $Path = $_.FullName
    $FileContent = Get-Content -Path $Path

    $SearchTerms | % {

        $SearchPattern = $_
        $FileContent | Select-String -Pattern $SearchPattern
    }
}

Additionally, I used a list of search terms but that could be replaced with a simple string search variable.

Sample output from this script:

grep