powershellget-eventlog

Filter EventLog based on date


I am trying to pull out some information from the eventlog through PowerShell based on the date today.

So far I have the code below:

$today = (Get-Date).ToString("dd/MM/yyyy")
Get-EventLog Security | where {$_.EventID -eq 4624} | where {$_.TimeGenerated -eq $today}

Now I have printed the result of today and can confirm that the outputted date is 04/12/2017, I have also printed the date of the TimeGenerated attriubute from the EventID object and that also shows the date in the same format.

Any ideas on where I am going wrong?


Solution

  • The TimeGenerated property holds a DateTime value, not a string, so don't compare it to a date string. Also, you should filter via Get-EventLog parameters whenever possible, because that filtering happens at the source. This is particularly relevant when querying remote eventlogs to reduce the amount of data that is transmitted over the network.

    $today    = (Get-Date).Date
    $tomorrow = $today.AddDays(1)
    
    Get-EventLog -LogName Security -InstanceId 4626 -After $today -Before $tomorrow