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-“.
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:
$startDir="C:\test_a"; 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.
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.
$startDir="C:\test_a"; Get-ChildItem -Path $startDir -Include *.tmp -Recurse | Select-String -Pattern "ORA-" -CaseSensitive
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