June 29, 2009

Microsoft LogParser 2.2 Tutorial IV

Click here to see part III.

In the past 3 tutorials, I talked a bit about using logparser straight from the console and querying various types of logs and CSV files. I have also shown how you can get various outputs of that data for example into a chart, csv, or just in the basic grid provided by logparser. In this next set of tutorials, I wanted to show how you can call logparser from code. The logparser API is actually not that bad and can be called in many ways and some examples even exist on the install (look at %%InstallFolder%%\Log Parser 2.2\Samples). I am first going to show you how to call logparser from Powershell. The good news is that a library exists for powershell and it is much easier to use the library then call it directly! So after you download the library, you can also create another script which can be called "LogParserUtils.ps1" (thanks to 'AC' for showing me this link from technet).
# http://blogs.technet.com/mscom/archive/2007/10/01/power-parsing-some-days-you-just-need-more-power-for-your-parser.aspx
function RecordsetToCVS($rs)
{
$LPResult= new-object System.Management.Automation.PSObject[] 0

while(!$rs.atEnd())
{
$rec = $rs.getRecord()
$LPResult += new-Object System.Management.Automation.PSObject

for($i = 0; $i -lt $rs.getColumnCount();$i++)
{
$LPResult[$LPResult.length-1] | add-member NoteProperty $rs.getColumnName($i) -value $rec.getValue($i)
}

$rs.moveNext()
}

$rs.close()

return $LPResult
}
Finally, it can be used like this:
function Test()
{
$query = @"
SELECT *
FROM \\MyServer\SYSTEM
WHERE TimeWritten > TO_LOCALTIME( SUB( SYSTEM_TIMESTAMP(), TIMESTAMP('01:15', 'hh:mm') ) )
"@

$inputformat = Get-LPInputFormat "EVT"
RecordsetToCVS (Invoke-LPExecute $query $inputformat)

}

Test
There you go, calling logparser from powershell is now a snap! This reminds me, I mentioned in a previous post that I was going to compare logparser to powershell on speed from getting information to an event log. I'll try and post that this week.

No comments:

Post a Comment