Powershell’s Select-String

One major disadvantage for Windows administrators is that they don’t get by default the same breadth of administrative tools which appear on pretty much any UNIX server.  One of these is grep.

There is a reasonable equivalent for one of the most common grep features—searching within text files for a particular regular expression.  You can use the Select-String cmdlet to look for text in a particular file.

To do a recursive search for the word “Discovery” in the current directory and all subdirectories, you would issue the following command:

Get-ChildItem - recurse | Select-String -pattern "Discovery";

To search in the current directory for files with a .sql extension and which contain “BEGIN TRAN” (to begin a transaction), you could run something like:

Select-String *.sql -pattern "BEGIN TRAN"

One of the examples provided by the Select-String help lets you parse the latest event log entries, looking for error messages. Given how slow the Event Log plugin can be, this can be a very good thing.

Get-EventLog -logname Application -newest 100 | Select-String -inputobject { $_Message } -pattern "Failed"

Unfortunately, it’s not as easy to do certain things as it is in grep, but at least it accepts piped input… And when you’re in an environment in which you can’t get one of the many Windows grep replacements.