Forum Discussion

Paul McLaughlin's avatar
Paul McLaughlin
Copper Contributor
Jun 15, 2017

Power Shell

Hello, 

I wanted to know if there is a script that can send an email when an event is log

  • 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
    }
    else
    {
    write-host "No error found"
    write-host "Here is the log entry that was inspected:"
    $event
    }

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

Resources