Today I was asked if there is any way of getting emailed if a particular Windows Event Log Event was generated on a server.
“Of course” I said, “SCOM can easily do that!”
“Oh we don’t have SCOM” was the reply.
“What? You don’t have SCOM? Why are you even talking to me?”.
Sadly this person was not in the position to use SCOM so he needed a different solution.
So one way handle this would be to use the in-built Task Scheduler to trigger based on the detection of the event and then we’d run a PowerShell script to email him. To do this would be quite simple. In Task Scheduler on the server we are to monitor, configure a new task. Make sure it’s set to Run Whether user is logged on or not (on the General Tab). On the Trigger tab set it to trigger on an event. In this case the requirement was to alert on the Windows Time Service Event ID 47 from the System Log as you see below.
Make sure you set it to “Enabled” of course and click “OK”.
On the Actions tab use the following:
Add arguments: -command “&’.\Send-Event.ps1′”
Start in: C:\Scripts (set this to the location of where you save the PowerShell script)
Now for the PowerShell Script we’re going to use to send the email. What I’m about to list is a very basic script but in all honesty it was all that was required, plus I had other things to do :).
All we really need is 3 things. A Subject and a Body for the email and the details of our mail server.
Well in this case you could populate the body of the email with anything you like. In this case he simply wanted some text indicating the error and the Time of the Event.
$TimeRaised = Get-Date
$ServerName = [System.Net.DNS]::GetHostByName(”).HostName
$Subject = “Microsoft-Windows-Time-Service Event ID 47 Detected on $ServerName”
$body = @”
Time Provider NtpClient: No valid response has been received from manually configured peer ntp.yourdomain.com after 8 attempts to contact it.
This peer will be discarded as a time source and NtpClient will attempt to discover a new peer with this DNS name. The error was: The peer is unreachable.
Alert Time Raised: $($TimeRaised)
# Send Email
$SmtpClient = New-Object Net.Mail.SmtpClient($smtpServer)
$mailmessage = New-Object system.net.mail.mailmessage
$mailmessage.subject = $Subject
$mailmessage.from = “firstname.lastname@example.org”
$MailMessage.IsBodyHtml = $false
$mailmessage.Body = $Body
Clear-Variable TimeRaised, ServerName, Subject, Body
I saved my script with the name of “Send-Event.ps1” and saved it to my C:\Scripts folder as you can see on our “New Action” tab above.
Finally of course I suggested that we test this by firing off a test event to the System Log that will match those 3 parameters. You will need to launchWindows PowerShell as Administrator in order to write to this log.
$evtDescription=”Test Event Description”
The end result was an email a few seconds later.
Hope that helps those of you that don’t have SCOM. Shame on you 🙂