Powershell Get-WinEvent cmdlt: Filtering by time-stamp not producing desired results

powershellwindows-event-log

I am trying to filter events via Get-WinEvent to get specific logs from the last 24 hours:

$EventLogFilter = @{logname='ForwardedEvents'; id=4771,4625,4768; StartTime=(Get-Date).AddHours(-24)}
$LogonEvents = Get-WinEvent -FilterHashtable $EventLogFilter

The problem is that Get-WinEvent only returns 14 events, but there are thousands that meet this criteria.

Example:

$EventLogFilter = @{logname='ForwardedEvents'; id=4771,4625,4768; StartTime=(Get-Date).AddHours(-24)}
$LogonEvents = (Get-WinEvent -FilterHashtable $EventLogFilter) 
$LogonEvents.count
14

Now, if I remove the StartTime filter from Get-WinEvent and filter with where-object you can see how many of these events there actually are:

$EventLogFilter = @{logname='ForwardedEvents'; id=4771,4625,4768}
$LogonEvents = (Get-WinEvent -FilterHashtable $EventLogFilter)
($LogonEvents | ?{$_.TimeCreated -ge (Get-Date).Addhours(-24)}).count
19497

So it missed almost 20,000 event logs! What the heck is going on, am I doing something stupid, is Get-WinEvent broken? Is there a limit to the number of logs this cmldet can filter before it freaks out and produces unreliable results?

Best Answer

Someone gave me the answer on another forum- FilterXML to the rescue.

The following gave me exactly what I wanted with added convenience of letting the GUI built the query for me:

$FilterXML = '<QueryList>
  <Query Id="0" Path="ForwardedEvents">
    <Select Path="ForwardedEvents">*[System[(EventID=4771 or EventID=4625 or EventID=4768) and TimeCreated[timediff(@SystemTime) &lt;= 86400000]]]</Select>
  </Query>
</QueryList>'
$LogonEvents = Get-WinEvent -FilterXml $FilterXML
$LogonEvents | sort -Property TimeCreated | Select-Object -First 1

Doing ($LogonEvents | sort -Property TimeCreated | Select-Object -First 1) I was able to confirm the oldest log was exactly 24 hours old.

Should have poked around in the docs more because I didn't event know about -filterxml. I think I'll be using that from now on.