Search code examples
powershellemailserverevent-viewer

PowerShell script to send me email alerts of Event Viewer errors/warnings/failures


I am trying to edit the script below to utilize the task scheduler send me an email notification every time an error/warning/failure is logged in our servers Event Viewer.

Important info:

  • I am brand new to PowerShell
  • The from email and to email are both apart of my company's outlook exchange server
  • I need this script to pull events from the "Windows" log folder in Event Viewer
  • I also believe this script requires a module installation, which I am struggling to figure out how to do
  • I need to know what to edit (I believe in the parameters) to make to fit my specific use case

Thanks in advance for any help at all. Here is the script from https://github.com/blachniet/blachniet-psutils/blob/master/Send-EventEntryEmail.psm1 :

Import-Module $PSScriptRoot\Send-EventEntryEmail.psm1

Function Send-EventEntryEmail {

[CmdletBinding()]
    param(
        [Parameter()]
        [string] $LogName = "System""Application""Security,
    
        [Parameter(Mandatory=$true)]
        [string] $Source,
    
        [Parameter()]
        [int] $Newest = 5,

        [Parameter()]
        [string[]] $EntryType = "Error""Warning""Failure",
    
        [Parameter(Mandatory=$true)]
        [string] $SmtpUser = "[email protected]",
    
        [Parameter(Mandatory=$true)]
        [string] $SmtpPassword = "passwordexample",
    
        [Parameter()]
        [int] $SmtpPort = 587,
    
        [Parameter()]
        [string] $SmtpServer = "smtp.mail.outlook.com",
    
        [Parameter(Mandatory=$true)]
        [string] $MailFrom = "[email protected]",
    
        [Parameter(Mandatory=$true)]
        [string] $MailTo = "[email protected],
    
        [Parameter()]
        [string] $Subject = "EventLogAlert",

    )

    # Get the event entries.
    $eventEntries = Get-EventLog -LogName $LogName -Source $Source -Newest $Newest -EntryType $EntryType

    # Create a table row for each entry.
    $rows = ""
    foreach ($eventEntry in $eventEntries){
        $rows += @"
        <tr>
            <td style="text-align: center; padding: 5px;">$($eventEntry.TimeGenerated)</td>
            <td style="text-align: center; padding: 5px;">$($eventEntry.EntryType)</td>
            <td style="padding: 5px;">$($eventEntry.Message)</td>
        </tr>
"@
    }

    # Create the email.
    $email = New-Object System.Net.Mail.MailMessage( $MailFrom , $MailTo )
    $email.Subject = $Subject
    $email.IsBodyHtml = $true
    $email.Body = @"
    <table style="width:100%;border">
        <tr>
            <th style="text-align: center; padding: 5px;">Time</th>
            <th style="text-align: center; padding: 5px;">Type</th>
            <th style="text-align: center; padding: 5px;">Message</th>
        </tr>
    
    $rows
    </table>
"@

    # Send the email.
    $SMTPClient=New-Object System.Net.Mail.SmtpClient( $SmtpServer , $SmtpPort )
    $SMTPClient.EnableSsl=$true
    $SMTPClient.Credentials=New-Object System.Net.NetworkCredential( $SmtpUser , $SmtpPassword );
    $SMTPClient.Send( $email )
}

Export-ModuleMember Send-EventEntryEmail

Below are the errors I get in ISE when I run this current script:

At line:17 char:34
+         [string[]] $EntryType = "Error""Warning""Failure",
+                                  ~
Missing ')' in function parameter list.
At line:35 char:49
+         [string] $MailTo = "[email protected],
+                                                 ~
Missing argument in parameter list.
At line:37 char:20
+         [Parameter()]
+                    ~
An expression was expected after '('.
At line:38 char:45
+         [string] $Subject = "EventLogAlert",
+                                             ~
Missing expression after ','.
At line:3 char:31
+ Function Send-EventEntryEmail {
+                               ~
Missing closing '}' in statement block or type definition.
At line:40 char:5
+     )
+     ~
Unexpected token ')' in expression or statement.
At line:78 char:1
+ }
+ ~
Unexpected token '}' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingEndParenthesisInFunctionParameterList

Solution

  • You can subscribe to Event Log via email by setting a scheduled task which will receive the notice of a new event and deliver it by email.

    From the Task Scheduler, you start by adding a task triggered by "On an event". To subscribe to a particular Log/Source/Event ID combination, use "Basic". To subscribe to many events, use "Custom" with an event filter meeting your needs.

    Event trigger

    Either way, the second step is a powershell script which can inspect the event and forward it by email. This can be done by adding an action in Task Scheduler which calls powershell.exe and passes the agruments .\MyDelightfulScriptName.ps1 -eventRecordID $(eventRecordID) -eventChannel $(eventChannel).

    Trigger

    Then follow bergerb's instructions to pass the event record ID and channel to powershell.

    To access the event that was logged, the powershell script uses Get-WinEvent with the EventRecordID filter:

    # Collects all named paramters (all others end up in $Args)
    param($eventRecordID,$eventChannel)
    
    $event = Get-WinEvent -LogName $eventChannel -FilterXPath "<QueryList><Query Id='0' Path='$eventChannel'><Select Path='$eventChannel'>*[System[(EventRecordID=$eventRecordID)]]</Select></Query></QueryList>";
    
    Send-MailMessage `
        -From '[email protected]' `
        -To '[email protected]' `
        -Subject ($event.Message.Split([Environment]::NewLine)[0]) `
        -SmtpServer 'smtp.domain.local' `
        -Body ($event.Message);