Monday, 20 April 2020

PowerShell Get Windows Events by Date

Hi Guys,

Yet another simple method to query the events with Generated Time and accessing other locations of Event Logs.

The most helpful scenario:
Get Events of specific source, check when the event had it's first occurrence in a day and the last across many days.

This is a helpful query, if a problem triggers specific events for certain time and to capture start and stop time of the problem.

Get the source of the Events Generated.

Capture all the Events to a variable.

$eventCapture = Get-EventLog <Logname> -Source <sourceName>
 Example : Get Logon time of a specific user in a day.

$eventCollector = Get-EventLog Security -Source Microsoft-Windows-Security-Auditing  -InstanceId 4624 -Message "*Administrator*"



For a given day, the below query would give when the first event occurred.

$eventCollector | Group-Object { $_.TimeGenerated.Date } | % { $_.Group | Sort-Object TimeGenerated | select -First 1 }

The first login attempt for the day.





For a given day, the below query would give when the last event occurred.

$eventCollector | Group-Object { $_.TimeGenerated.Date } | % { $_.Group | Sort-Object TimeGenerated | select -Last 1 }

 


Comparing the above two results, we know when the user first logged in and last logged in for the day, we could however customize more.

In a repeating incident, this could help to get vital details of the event occurrances.

Happy Scripting.