I needed a simple script to backup a server running Windows Server 2008 to a network location with email reports.
At first I did some prerequisites(the steps marked with * at the beginning aren’t absolutely necessary):
*1. Create a CNAME on my dns for the server where the backups reside: backup.mydomain.com .
2. Create a share on the backup server.
3. Create the folder structure for the backups: on the root of the share create a folder named exactly as the server (the result of hostname command on the backed up server); create in this folder 7 other folders named by each day of the week -monday, tuesday,wednesday, thursday, friday, saturday, sunday.
function SendEmail($To, $From, $Subject, $Body, $attachment, $smtpServer)
Send-MailMessage -To $To -Subject $Subject -From $From -Body $Body -Attachment $attachment -SmtpServer $smtpServer
$backuplog="$backuplocation"+(get-date -f MM-dd-yyyy)+"-backup-$hname.log"
Write-Output ("———————– Backup started on – $(Get-Date –f o) ————————-") | Out-File "$backuplog" -Append
wbadmin start backup -backupTarget:$backuplocation -include:"d:,e:" -allcritical -vssfull -quiet | Out-File "$backuplog" -Append
Write-Output ("———————– An error has occurred! Check it please!. – $(Get-Date –f o) ————————-") | Out-File "$backuplog" -Append
SendEmail -To "$emailto" -From "$emailfrom" -Subject "backup failed" -Body "The backup has failed! Please check attached log." -attachment "$backuplog" -smtpServer "$emailserver"
Write-Output ("———————– Everything is OK! – $(Get-Date –f o) ————————-") | Out-File "$backuplog" -Append
SendEmail -To "$emailto" -From "$emailfrom" -Subject "backup $hname ok" -Body "The backup has succeeded!" -attachment "$backuplog" -smtpServer "$emailserver" .
Save it as a yourname.ps1 file and create the scheduled task accordingly to your needs. Below how you should start the task from the schedule tasks Actions.
If your smtp server requires authentication create a separate account for this and update the SendEmail function so that it includes the
As you can see all the variables are defined at the start of the script:
$hname – is the name of the host that’s backed up
The rest of the variables are pretty straightforward.
What does the script:
1. Backup to a network location of your choice.
2. Create a backup log.
3. Check if the backup ended successfully/unsuccessfully.
4. Send an email with the result: success/failure and the log is attached.
Of course if you need to keep the backups more than a week you’ll have to copy them from there since wbadmin clears the folder where it creates the backup.