Send windows event log with HTML formatting (PowerShell)

This example sends Windows Backup logs

$Yesterday = (Get-Date) - (New-TimeSpan -Day 1)
$logs = Get-WinEvent -logname Microsoft-Windows-Backup | Where-Object {$_.TimeCreated -ge $Yesterday} 
$username = "user@domain.com"
$password = "mypassword"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$errorCount = 0
foreach($Event in $logs)
{
$Errorlevel=$Event.LevelDisplayName
    if ($Errorlevel -eq "Error")
        {
        $errorCount++
        }
}


$body = "<html>"
$style = "<style>BODY{background-color:white;}.error{color: red;font-weight: bold;}table, th, td{border: 1px solid black;border-collapse: collapse;padding: 5px;}</style>"
$head = "<head>$style</head>"
$body += $head
$body += "<body>"
$body += "<h2>$env:computername Backup Logs</h2>"
if ($errorCount -gt 0)
    {
    $body += "<h3 class=""error"">$errorCount Errors</h3>"
    }
$body += "<table><tr><td>Time</td><td>Error Level</td><td>EventId</td><td>Message</td></tr>"
        # Get the event Log Details
        foreach($Event in $logs)    
        {
            $Time=$Event.TimeCreated
            $Errorlevel=$Event.LevelDisplayName
            $EventId=$Event.Id
            $Message=$Event.Message
            $TableLine = "<tr><td>$Time</td><td>$Errorlevel</td><td>$EventId</td><td>$Message</td></tr>"
            if($Errorlevel -eq "Error")
            {
                 
                $TableLine = "<tr class=""error""><td>$Time</td><td>$Errorlevel</td><td>$EventId</td><td>$Message</td></tr>"
            }
                                  
            $body += $TableLine
        }
$body += "</table>"
$body += "</body>"
$body += "</html>"
#echo $body
 
$subject = "$env:computername Backup Logs"
if ($errorCount -gt 0)
    {
    $subject += " - $errorCount Errors"
    }
 
Send-MailMessage -BodyAsHTML $body `
-From me@domain.com `
-SmtpServer mail.server.com`
-Subject $subject `
-To "me@domain.com" `
-UseSsl -Credential $cred

Leave a Reply