PowerShell to send an email when something happens in the Event Log.

Most larger companies have SCOM or some other monitoring tool in place to watch over SharePoint servers and let the right people know when things go wrong.

That said, there are times when you just need a quick and dirty way to get notified when something shows up in the event log – It might be something temporary, or something you are asked to watch – but to keep under the radar – Or maybe the SCOM team has a backlog and you need to know you’ll be alerted before you go home for the day.

Here is an extremely simple script that can be used in conjunction with Event Viewer to send an email.

Here’s how it works:

1) In Event viewer, find the event log you want to watch. Find the event you are looking for and right click it and choose “Attach a Task To this Event…”

2) Follow the wizard and when you get to the part about what to do, you can choose the default email option, or if you want to add some additional logic, choose to “Run a program”

3) Copy the contents of the script below to a file with a .ps1 extension and alter the script to fit your specific use case.

4) Specify c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe as the name of the executable (do this even if you are using a later version of powershell)

5) Specify the path and name of the script file you created above as the parameter.

$event = get-eventlog -LogName Application -source "Put your source here" -newest 1
#get-help get-eventlog will show there are a handful of other options available for selecting the log entry you want.
if ($event.EntryType -eq "Error")
    $PCName = $env:COMPUTERNAME
    $EmailBody = $event.Message
    $EmailFrom = "Your Return Email Address <$PCName@yourdomain.com>"
    $EmailTo = "youremail@yourdomain.com" 
    $EmailSubject = "Your Event Log event was found!"
    $SMTPServer = "mailserver.yourdomain.com"
    Write-host "Sending Email"
    Send-MailMessage -From $EmailFrom -To $EmailTo -Subject $EmailSubject -body $EmailBody -SmtpServer $SMTPServer
    write-host "No error found"
    write-host "Here is the log entry that was inspected:"

Now, anytime the event you specified is found in the log, your script will be triggered.

The first line of the script fetches the most recent log item that matches some core criteria, it’s important to refine this as much as possible, so that you’re not emailing yourself details of event you want and not an event that showed up a split second later.

Final Thoughts:

This is a simple solution, for simple scenarios. I can attest that it’s worked great for me, for my limited scope scenario.  My company also uses SCOM to alert us on the more normal SharePoint issues – I’m not advocating this as a replacement for proper monitoring, but used in the right scenarios, it can be an extra tool available to you.

– Jack

Leave a Reply