Windows Server backup / Email script

For many admins, they run into the issue of not being able to send automatically send backup reports to themselves since there is no inherent way to do so in Windows Server 2008-2012 R2.

Script:

The first thing we need is the script that will collect backup info and create an email with attachment.

Here is that code:

# Set up variables
$SmtpServer = "Your email server"
$SmtpPort = 25
$FromEmail = "source@fabrikam.com"
$ToEmail = "destination@contoso.com"
$OutputFile = "C:\Backup File Output\Backup.txt"
# Create backup results file
Get-PSSnapIn -Registered | Add-PSSnapIn -Name windows.serverbackup
$NextBackup = Get-Date (Get-WBSummary | select "NextBackupTime" | ft -hide | out-string)
$LastBackup = (Get-Date $NextBackup) - (New-TimeSpan -day 1)
Get-WinEvent -LogName "Microsoft-Windows-Backup" | Where {$_.timecreated -ge $LastBackup} | Sort-Object TimeCreated | Format-Table TimeCreated, Message -AutoSize -Wrap | Out-File $OutputFile
# Construct and send email
$SmtpClient = new-object system.net.mail.smtpClient
$Msg = new-object Net.Mail.MailMessage
$SmtpClient.host = $SmtpServer
$SmtpClient.Port = $SmtpPort
$computer = gc env:computername
$Msg.From = $FromEmail
$Msg.To.Add($ToEmail)
$Msg.Subject = "Backup Complete on " +$Computer
$Msg.Body = "The backup for " +$Computer+" has completed. Please see the attached file for backup results."
$Msg.Attachments.Add($OutputFile)
$SmtpClient.Send($Msg)

Open up notepad > copy + paste > save as filename.ps1

Once completed, you will need to setup a scheduled task that tracks Event IDs 4 and 5 which determines backup success or failure respectively.

Here are some examples:

Unknown Unknown-1 Unknown-2

Post Author: Cody Romero