Grep in PowerShell

I did some Oracle work recently which meant running some scripts on a test database, spooling the output to a log file in a local directory. Afterwards I realised it would be helpful if I could check all of the log files for any error messages.

Oracle error messages come in the form of, for example:

ORA-21300: objects option not installed

Using the PowerShell Select-String Cmdlet would allow me to emulate the Unix grep command and do a search through my log files for a search pattern of “ORA-“.

Code 1

The first variant of code used, gives a listing of the files found that contain the search pattern and a count of how many times it appears in each file.

Using the code:


Get-ChildItem –Path $startDir -Include *.tmp -Recurse |
    Select-String –Pattern "ORA-" -CaseSensitive |
    Group-Object path | Select-Object name, count |
    Format-Table -AutoSize;

gives an output something like:

Name                          Count
----                          -----
C:\test_a\test_d\test_d01.tmp     1
C:\test_a\test_h\ian2.tmp         3
C:\test_a\test_k\ian.tmp          1

File ian2.tmp for example, contains the search pattern three times.

Code 2

The next piece of code used, will give an output of:

  • Path and filename
  • Line number at which the search pattern was found.
  • The text of the line found.

Get-ChildItem -Path $startDir -Include *.tmp -Recurse |
    Select-String -Pattern "ORA-" -CaseSensitive

Sample output

C:\test_a\test_d\test_d01.tmp:2:ORA-21300: objects option not installed
C:\test_a\test_h\ian2.tmp:4:ORA-hello world ora
C:\test_a\test_h\ian2.tmp:6:ORA-helen message
C:\test_a\test_h\ian2.tmp:8:ORA-another ora message
C:\test_a\test_k\ian.tmp:2:ORA-32803: value for string cannot be altered

The class Microsoft.PowerShell.Commands.MatchInfo is returned by the Select-String cmdlet and provides information about the results of a match.

Keywords: powershell grep search string

This entry was posted in powershell and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s