Wednesday, December 17, 2014

Parsing Log File with PowerShell

Interesting article

http://matthewyarlett.blogspot.co.uk/2014/11/quick-and-dirty-parsing-logs-with.html

here is the code for reference

# Set the path to the log files            
$path = "C:\Temp\Logs"
# Get a collection of all the log files (anything ending in .log)
$files = Get-ChildItem -Path $path -Filter "*.log"
# Pipe the collection of log files to the ForEach-Object cmdlet
# (the alias of ForEach-Object is %)
$files | %{
# Call the OpenText method, to return a System.IO.StreamReader object
$file = $_.OpenText();
# Record the current line number (to use in the console output)
$lineNum = 1;
Write-Host "Checking file"$_.Name -f Yellow;
# Use the EndOfStream method (which returns true when you have reach the end
# of the file), read each line of the file.
while($file.EndOfStream -ne $true)
{
# Read the next line in the file
$line = $file.ReadLine();
if($line -ne $null)
{
# Use the String ToLower and Contains methods to check for occurances
# of the strings (or values) you need to check the file for
# In this example, I'm looking for any instances of the text "error" or "exception"
if($line.ToLower().Contains("error") -or $line.ToLower().Contains("exception"))
{
# If the current lines contains a match, write the line number
# and line text out to the console
Write-Host "Line: $lineNum " -NoNewline -ForegroundColor Green;
Write-Host $line -f Red;
}
}
# Increment the line number
$lineNum++;
}
}