Skip to content

Instantly share code, notes, and snippets.

@mbrownnycnyc
Last active August 29, 2015 14:07
Show Gist options
  • Save mbrownnycnyc/2f95b53585541e22b477 to your computer and use it in GitHub Desktop.
Save mbrownnycnyc/2f95b53585541e22b477 to your computer and use it in GitHub Desktop.
This is a local (or remote) querier of machines to check for critical and error events in the system event log. If found, it will send errors in a decently/readably formatted email to a given address.
$computer = $env:COMPUTERNAME
$checkintervalmins = 60
$checkintervalms = (new-timespan -minutes $checkintervalmins).totalmilliseconds
#http://www.mcbsys.com/techblog/2011/04/powershell-get-winevent-vs-get-eventlog/
#http://technet.microsoft.com/en-us/library/hh849682.aspx
#generated by "Create Custom View" in any Event Viewer
#we will check events:
# from system log
# that are errors or critical
# that happened in the last 30 minutes (1800000 milliseconds, 60 mins = 3600000 ms)
# excluding events with eventid 1111
$xmlquery = [System.Xml.XmlDocument]"`
<QueryList>
<Query Id='0' Path='System'>
<Select Path='System'>*[System[(Level=1 or Level=2) and TimeCreated[timediff(@SystemTime) &lt;= $checkintervalms]]]</Select>
<Suppress Path='System'>*[System[(EventID=1111)]]</Suppress>
</Query>
</QueryList>"
#http://technet.microsoft.com/en-us/library/ff730948.aspx
$events = get-winevent -computer $computer -FilterXML $xmlquery | select providername,@{Name='Level';E={$_.leveldisplayname}},id,@{name='TimeCreated';E={ ($_.timecreated).tostring("hh:mm:ss") } },message -ea silentlycontinue
#if the query returned results
if ($events) {
#ze email boss, ze email
# TH {border-width: 1px;padding: 3px;border-style: solid;border-color: black;background-color: #6495ED;}
#http://thesurlyadmin.com/2013/01/21/how-to-create-html-reports/
$Header = "`
<style>
TABLE {border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}
TH {border-width: 1px;padding: 3px;border-style: solid;border-color: black;background-color: #781500;}
TD {border-width: 1px;padding: 3px;border-style: solid;border-color: black;}
.odd { background-color:#ffffff; }
.even { background-color:#dddddd; }
</style>
<title>
</title>"
send-mailmessage -smtpserver $smtpserver -to $to -from $from -subject "Error event logged in last $checkintervalmins minutes [$computer] " -bodyashtml -body ( $events | convertto-html -head $Header | out-string )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment