Powershell: Email event logs to X


One of the things that has bothered me for awhile is trying to get across the sheer quantity of servers I have and making sure they are all happy.  There are a lot of tools and bits of software, most use agents, to monitor how well your server is feeling.  Being the cheapskate I am I thought I’d write a powershell script to just email me the days event logs that have either warning, error or critical.  If the email doesn’t come through then we know there’s something up with the mail server :p

So, here is the quick script:

# Email Warnings, Errors and Criticals from each server to an SMTP address
#
# Make sure you create a credential file by doing a "read-host -assecurestring | convertfrom-securestring | out-file C:\scripts\crendentials.txt"
# so you can run this script automated.

$username = "domain\user"
$password = cat C:\scripts\credentials.txt | convertto-securestring
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password

# Create the reporting CSV files. Add new server names or IPs to $s line below
$s = "server01", "server02"
Foreach ($server in $s) {$server; Get-WinEvent -MaxEvents 200 -EA silentlycontinue -Computername $server -Credential $cred |
?{$_.Level -eq 2 -or $_.Level -eq 3 -AND $_.TimeCreated -gt [datetime]::today} | Select-Object TimeCreated, ID, ProviderName, Message | export-csv "C:\scripts\reports\$server.csv" }

#Send-MailMessage -To $smtpaddress -From $smtpfrom -Subject "Server Event Logs" -Attachments "c:\scripts\argononbackup.csv", "c:\scripts\argononfs1.csv" -SmtpServer $smtpserver -priority High -dno onSuccess, onFailure
$smtpserver = "MailServerName"
$msg = new-object Net.Mail.MailMessage
$smtp = New-Object Net.Mail.SmtpClient($smtpserver, 25)
$msg.Priority = [System.Net.Mail.MailPriority]::High
$msg.From = "[email protected]" #From email address
$msg.To.Add(“[email protected]”) #To email address
$msg.Subject = "Event Log Errors, Warnings and Critical" # Email subject line
$msg.Body = "Attached files are today's logs" # Body of email

# Attach all the CSV files from the c:\scripts dir
$files=Get-ChildItem “C:\scripts\reports\”
Foreach($file in $files)
{
$attachment = New-Object System.Net.Mail.Attachment –ArgumentList C:\scripts\Reports\$file
$msg.Attachments.Add($attachment)
}
$smtp.Send($msg) # Send the email
$attachment.Dispose(); # discard attachments
$msg.Dispose(); # finish the email command

So, there we go.

Leave a comment