Full backups of running Hyper-V guests
Mon, Nov 16, 2009I’ve written a Powershell script to execute the diskshadow script I mentioned earlier, and implemented a couple of ideas I had.
This script will create full backups of Hyper-V guests while they are running.
First, this script will check to see if the destination folder has any VHDs that were backed up more than 10 days ago (since this runs every two weeks it will remove the oldest of the two backups that are stored). It then starts the diskshadow script that mounts a shadow copy of the drive storing the virtuals to another drive (the Z: in my script below). Finally, it copies the VHDs from the Z: to a folder on another drive (the destination in this case is the D:) and labels the folder by date.
Here is the main Powershell script: vhdfull.ps1
#Set Date Variables<br />
$folderdate = get-date -uformat "%m-%d-%y"<br />
$Now = Get-Date<br />
$DelDate = $Now.AddDays(-10)
#Start Transcript<br />
start-transcript -path c:vhdscripttmp.txt
#Look at destination folder and remove older backups<br />
Get-ChildItem D:VHDBackups |Where {$_.CreationTime -le "$DelDate"}|remove-item -recurse -Verbose<br />
remove-item c:\vsbackup\tmp2.txt
#Run diskshadow, and save log for pushing into string builder for e-mail alert<br />
diskshadow /s c:\vhdscriptvhdshadow1.txt >> c:\vsbackuptmp2.txt
#Copy the files from the disk shadow copy.<br />
Copy-Item Z:virtuals D:VHDBackups$folderdate -recurse -Verbose
#End Transcript<br />
stop-transcript
#Remove Disk Shadow<br />
diskshadow /s c:vhdscriptvhdshadow2.txt
<br />
#Create string builder to format logs<br />
$strbuild = new-object System.Text.StringBuilder
#Add line breaks to both logs, and glue them together<br />
foreach ($line in get-content "C:vhdscripttmp2.txt")<br />
{<br />
$strbuild.Append($line).Append("<br/>")<br />
}<br />
foreach ($line in get-content "C:vhdscripttmp.txt")<br />
{<br />
$strbuild.Append($line).Append("<br/>")<br />
}
#Send it.<br />
$message = new-object System.Net.Mail.MailMessage("VHDBackup@localhost", "[email protected]")<br />
$message.Subject = " - VHDBackup"<br />
$message.IsBodyHtml = $True<br />
$message.Body = "<font size=2 face=Arial>"+$strbuild<br />
$smtp = new-object Net.Mail.SmtpClient("<IP OF SMTP SERVER HERE>")<br />
$smtp.Send($message)
Here is the first diskshadow script: vhdshadow1.txt
set context persistent<br />
add volume e: alias VHDs<br />
set verbose on<br />
create<br />
expose %VHDs% z:
… and the second: vhdshadow2.txt
delete shadows all