I recently had a need to send email notifications on a Windows 2003 server when a backup through NTBackup failed. Preferring PowerShell to VBscript, I installed PowerShell on the server, and set out to script the notification.
I decided to send a notification based on whether or not the NTBackup application has logged an error in the application event log in the past 24 hours. I chose this way because in Windows 2008 and later, there is a built-in scheduled task that can be customized to send an email based on an event ID, and I am already using this on some other servers. So it made sense to keep the same method of notification in Windows 2003.
I could have also chosen to parse through the ntbackup log and look for errors, or check for the existence of a new backup file created within the last 24 hours.
I didn't find a PowerShell version of NTBackup notification anywhere else online, and many of the VBscript versions require using blat. One advantage of the PowerShell method is that you don't have to install anything third party on the server. All you need is PowerShell.
Please note this script works only with PowerShell 2.0, and only in versions of Windows 2003 and 2003 R2. In this version of the script, I am storing the SMTP account and password in plaintext (of course I didn't put a real account in the script below!), so if this is a problem in your network, I would suggest using get-credential to pass the credential in a secure manner instead.
'Set the computer name
$computer = gc env:computername
'Set Email parameters
$EmailFrom = "backup_service@chrislehr.com"
$EmailTo = "robin.lehr@chrislehr.com"
$Subject = "Backup Failed on " + $computer
$SmtpServer = "mail.chrislehr.com"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Credentials = New-Object System.Net.NetworkCredential("backup_service","P@ssw0rd")
'Find all NTBackup events in the event log within the last 24 hours with type error. If the count is greater than 0, send an email.
$events = get-eventlog -computer $computer -LogName application -after (get-date).addhours(-24) -EntryType error| where-object {$_.source -eq "ntbackup"}
$body = "A Backup job has failed on " + $computer + "in the past 24 hours. Please investigate"
If (($Events).count -gt 0) {$smtp.Send($emailFrom, $EmailTo, $Subject, $body)}
No comments:
Post a Comment