Search code examples
powershellpowershell-cmdlet

Powershell Get-EventLog (Intro)


Sorry I am just starting out writing a PowerShell scripts. I am trying to use a script to send a email once an event (error) comes across the Event Viewer. I do not want to use the feature that is incorporated in Event Viewer because it does not work on all Operating Systems. Here is what I have in my script now but I cannot import the Message or Data from the error that cut.

$event = Get-EventLog -LogName Application -Source "My Script-1" | where {$_.eventID -eq 1}

if ($event.EntryType -eq "Error")
{
    [string]$EmailBody = Event.Data
    $EmailFrom = "Test@google.com"
    $EmailTo = "lmill130@kent.edu"
    $EmailSubject = "This was sent from a PowerShell Script"
    $SMTPServer = "Example Server SMTP"
    Write-host "Sending Email Test"
    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
}

If I put my own string in $EmailBody then it works with no issue but when I try to grab data from the Event I have no luck.

This is the script I use to create the test event.

#New-EventLog -LogName Application -Source "My Script-1" 
Write-EventLog -LogName Application -Source "My Script-1" -EntryType Error -
EventId 1 -Message "This is a test Entry." 

I have a task created that when that event cuts then it runs the first script.

I have searched all over the internet and I have had no luck. Help please.


Solution

  • Thats probaly because Event.Data doesn't return anything.

    It has to be $event.Data, but I think you should maybe use $event.Message to get the info message of the error.

    So all together would look like this:

    $event = Get-EventLog -LogName Application -Source "My Script-1" | where {$_.eventID -eq 1}
    
    if ($event.EntryType -eq "Error")
    {
        [string]$EmailBody = $event.Data
        #or [string]$EmailBody = $event.Message
    
        $EmailFrom = "Test@google.com"
        $EmailTo = "lmill130@kent.edu"
        $EmailSubject = "This was sent from a PowerShell Script"
        $SMTPServer = "Example Server SMTP"
        Write-host "Sending Email Test"
        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
    }