Emulating grep with PowerShell

I’m a big fan of PowerShell with it’s nifty object pipeline, but there are some quick and dirty tasks it could make easier. As and example, I was looking for a way to recursively search through directories, looking at the contents of files for a specific string.

Accomplishing this took a little poking around the Internet, but ultimately I found a great blog post describing how to do it. You need to to use a combination of get-childitem (abbreviated gci) and select-string. From Marshall’s post:

The grep command grep -R "mypattern" *.cpp can be translated to the PowerShell command:

gci . --include *.cpp -recurse | select-string -pattern "mypattern" -caseSensitive

Note that “.” can be replaced with an arbitrary path as opposed to the current directory and you might want to leave off -caseSensitive if you don’t care about case. You can also omit --include *.cpp to include all files.

  1. As a final param to the select-string command -List will reduce the output to show the files that contain the instance without showing _every_ instance.

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>