Hyper-V VM Backup Script Batch File

12 Mar

If you’re after a way to make good, non corrupt backups of your Hyper-V VM’s, and you after a way of doing it for free, then this script is what you want.

This script will shut down your selected VM’s (simply enter the machine names into a text file), it will then copy the .vhd files (you need to enter the .vhd file names and locations into the batch file) to wherever you specify and then it will power the virtual machines back on again. I’m not currently using this myself, although I did run a test the other day and it worked perfectly.

So, I simply run a scheduled task to run over night, which calls this batch file:

REM Hyper-V Virtual Machine Backup

REM Shutdown virtual machines
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe d:\scripts\vmbackup\StartStopVms.ps1 d:\scripts\vmbackup\VmNamesStop.txt 1

REM Now copy VHD’s to \\machine\g$\VHD
c:
net use b: /delete /y
net use b: \\machine\d$\VHD
copy /Y “d:\VHD\*.vhd” b:\

REM Power on virtual machines
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe d:\scripts\vmbackup\StartStopVms.ps1 d:\scripts\vmbackup\VmNamesStart.txt 0

REM Finished!

Its all pretty straightforward stuff and works really well.

Full details (and a download of the files) can be found here.

Update…

To set the scheduled task, I ran this command:

c:\>schtasks /create /tn “VmBackup” /tr “e:\scripts\VmBackup\VmBackup.bat” /sc Weekly /D Mon /st 01:00 /RU ****\******** /RP ********

(Use /RU and /RPA rather than /U and /P, A nice little guide can be found here) That will then run the VmBackup task every Monday morning at 1am. When I get into work, I then copy all the VHD’s to tape and take them off-site.

A few other commands, delete the Scheduled Task:

c:\>schtasks /tn “VmBackup” /delete

Run the scheduled task:

c:\>schtasks /tn “VmBackup” /run

PS, I recieved the error “script.ps1 cannot be loaded because the execution of scripts is disabled on this system”, to get around this, run “powershell.exe” from the command line tand then run “Set-executionPolicy RemoteSigned”.

Update: On server 2008 I had a few issues just calling the .bat from the scheduled task. It seems I wasn’t the only one either, see here. I ended up entering the batch file name and then moving the path to the “Start in” field, that seemed to fix it.