Monday, 9 February 2009

Querying event logs with Powershell

Last week I had the opportunity to talk through a Powershell script with a couple of members of my team. The script itself was one I had written to trawl through all of the event logs on my main Vista notebook and to just report back any entries flagged as Errors, with a parameter of n where n is the number of days that the script was to go back through. Once I'd explained that the first 30 lines were comments and the built-in help it was apparent that this was actually the perfect way to demonstrate what Powershell is capable of. Right at the heart of the script is nothing more than a simple cmdlet that demonstrated the verb-noun principle ie: what do you want to do? - what do you want to do it to?
So I started off by simply showing what happens when you run get-eventlog from the Powershell prompt:
get-eventlog Application

then restricting it to just errors:

get-eventlog Application where {$_.EntryType -eq "Error"}

and then to limit the numbers of days to check back through (in this case 3 days):
$date = Get-Date
$recent= $date.AddDays(-3)
Get-EventLog Applicationwhere {($_.TimeWritten -ge $recent) `
-AND ($_.EntryType -eq "Error")}

And so the rest of the session went on, also going through how the script built an array of the available logs and then iterated through each one in turn. End result was that they now had PS script that could quickly check a machines event logs for errors (GUIs are so overrated), but more importantly they had a useful and relevant intro to Powershell (as well as a good understanding of how the script worked).
And the most important cmdlet that I told them about (almost a dozen times)?

get-help

No comments:

Post a Comment