Thevagabond Thevagabond - 3 months ago 16
PowerShell Question

Filter activity log entries by day and time span with power shell

I have the following working power shell command:

Get-Eventlog -Logname system -Source user32 | Select TimeGenerated, EntryType, Message


However I only want entries from monday to friday and between 6am and 4pm.
How can I filter those entries.

Thanks for your help.

TheVagabond

Answer

If you do not want to create a date boundary:

Get-Eventlog -LogName system -Source user32 |
    Where-Object { $_.TimeGenerated.DayOfWeek -ge ([DayOfWeek]'Monday') -and $_.TimeGenerated.DayOfWeek -le ([DayOfWeek]'Friday') -and $_.TimeGenerated.Hour -ge 6 -and $_.TimeGenerated.Hour -lt 16 } |
    Select-Object TimeGenerated, EntryType, Message

Creating a date boundary may be more efficient, especially if you only wanted to go back for a few weeks, that would feed the Before and After parameters on Get-EventLog. Using Where-Object for that is less efficient.