Filtering Events by Date and Time

by Mar 11, 2009

As you have discovered in a previous tip, reading Eventlog entries is fairly simple using WMI and Win32_NTLogEvent:

Get-WmiObject Win32_NTLogEvent -filter "LogFile='System' and EventType=1" |
Format-Table ComputerName, EventCode, Message, TimeWritten

This will retrieve all events that meet your filter criterion. Sometimes, though, you might want to just see all relevant events that have occurred within the past 24 hours. How can you filter by date or time?

Since every event has a TimeGenerated and a TimeWritten property, you can use these properties in your filter as well. All you need do is specify dates and times in the special WMI datetime format. Luckily, it is fairly simple to convert a regular time expression into WMI format. The next line generates the WMI time of now minus 24 hours:

$time = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime((Get-Date).AddHours(-24))
$time

Here's another example: to see all error events from all eventlogs that have occurred within the past 24 hours, try this:

$time = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime((Get-Date).AddHours(-24))
Get-WmiObject Win32_NTLogEvent -filter "EventType=1 and TimeGenerated>='$time'" |
Format-Table LogFile, Message, EventCode, TimeGenerated -wrap