Technical : Microsoft – Event Log / Event Viewer – Query via PowerShell

Technical : Microsoft – Event Log / Event Viewer – Query via PowerShell

Introduction

After my fiasco of not paying attention to my Event Log, I need a quick way to aggregate Event Log entries and here is what I came up with through curating Google web postings.

Code



# PowerShell example which groups event then sorts in descending order.
Clear-Host

$logName = "System"

#get date
$dateCurrent = Get-Date

#For the Week
$NDays = -7
$dateNDaysAgo = $dateCurrent.AddDays($NDays)

Write-Host "Log Entries since $dateNDaysAgo"

Get-WinEvent -Logname $logName  | `
where-object { $_.timecreated -gt $date  -and $_.levelDisplayName -in "Critical", "error", "warning" } | `
Group-Object ProviderName, levelDisplayName, ID | `
Sort-Object Count -descending | `
Format-Table Count, Name -auto

Output:

EventLogAggregator

Conclusion

And, yes I have too much time on my hands, and not enough brains; as I need Splunk, Nagios, or System Center.

Addendum

Addendum – 2014.01.20

Tried the code above on an MS Windows Vista Machine, but unfortunately it failed.

The original code was developed and targeted an MS Windows 2012 box.

The error message we got on the Vista box read:


You must provide a value expression on the right-hand side of the '-' operator.
At C:\temp\eventvwr.ps1:16 char:68
+ where-object { $_.timecreated -gt $date  -and $_.levelDisplayName - <<<< in "
Critical", "error", "warning" } | `
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : ExpectedValueExpression

To Correct:



# PowerShell example which groups event then sorts in descending order.
Clear-Host

$logName = "System"

#get date
$dateCurrent = Get-Date

#For the Week
$NDays = -7
$dateNDaysAgo = $dateCurrent.AddDays($NDays)

$logLevel = @("Critical", "Warning", "Error")
$logLevelCritical = "Critical"
$logLevelWarning = "Warning"
$logLevelError = "Error"

Write-Host "Log Entries since $dateNDaysAgo"

Get-WinEvent -Logname $logName  | `
where-object {   ($_.timecreated -gt $date)  `
                 -and ( `
                       ($_.levelDisplayName -eq $logLevelCritical)  `
                   -or ($_.levelDisplayName -eq $logLevelWarning)   `
                   -or ($_.levelDisplayName -eq $logLevelError)     `
                      )  } | `
Group-Object ProviderName, levelDisplayName, ID | `
Sort-Object Count -descending | `
Format-Table Count, Name -auto

References

Event Log

WMI

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s