I recently helped a fellow scripting admin with a PowerShell problem in the ScriptingAnswers.com PowerShell forum. He wanted to get Errors and Warnings that had happened in the last 30 minutes. Using the Get-EventLog cmdlet would seem like the write solution but it takes a little wrangling to get the information you want. One of the first challenges is that there does not appear to be a way to specify more than one logfile. The -logname parameter does not take a wildcard or multiple values. However, you can get a list of logfile names with -list. That might be promising. I can create an object that contains a list of all the logfiles on my system like this:
$logfiles=Get-EventLog -list -asString
I use -asString because I want just the name of the logfile, not the logfile object. Now, what about filtering by the TimeWritten property? That is actually pretty easy. A datetime object has several methods such as AddDays,AddHours and AddMinutes. All I need to do is add a negative number of minutes from the current time like this:
$d=Get-Date
$lastweek= $d.AddDays(-7)
This will create an object ($lastweek) that is a datetime value of 7 days ago from now. Next I need to filter out just Warnings or Errors. Each eventlog entry object has a property of EntryType. All I need to do is find entries where EntryType -eq “Error” or EntryType -eq “Warning.”
Maybe you can see where I’m heading with this. Here’s script:
$d=Get-Date
$recent= $d.AddDays(-1)
$logfiles=Get-EventLog -list -asString
foreach ($log in $logfiles) {
Write-Host -foregroundcolor Red -backgroundcolor Yellow `
$log.ToUpper() “Event Log”
Get-EventLog -logname $log | where `
{($_.EntryType -eq “Warning” -OR $_.EntryType -eq “Error”) `
-AND ($_.TimeWritten -ge $recent)}
}
This script will display all errors and warnings from all event logs on my system that occurred within the last day. The heavy lifting is done by this Where expression:
where {($_.EntryType -eq “Warning” -OR $_.EntryType -eq “Error”) -AND ($_.TimeWritten -ge $recent)
The expression has some compound queries. First I need events where the type is either Warning or Error and then the TimeWritten must be greater or equal to a datetime value of 1 day ago.
You can easily modify the script for a different time range, specific log files or specific log types. If you’re wondering how I knew what the eventlog properties were, you can see for yourself with a command like this:
get-eventlog -logname application -newest 1 |get-member
You can modify the query accordingly if you want to display additional information.
The downside to Get-Eventlog is that it only works on the local system. I’ll show you how to take another approach if you want to query a remote server another day.