A simple script to backup a Virtual Server

A common question is how to quickly and easily backup a virtual machine under Virtual Server.  There are a number of ways to do this – each of which have their own advantages and disadvantages. 

Today I am going to show you how to have a simple script that ‘save states’ a virtual machine, copies the virtual machines files, and restores the virtual machine.  The advantage of this approach is that it will work no matter what guest operating system you are running – however the disadvantages are that it will take the virtual machine offline for a period of time, and depending on the size of the virtual machine it may take a while to make the backup copy. 

This script takes two command line parameters – the first one being the name of the virtual machine to backup, while the second one is the name of the path to backup to:

‘Script Begins

On Error Resume Next

‘Create Shell Object
Set objShell = CreateObject (“WScript.Shell”)

‘Connect to Virtual Server
Set virtualServer = CreateObject(“VirtualServer.Application”)

‘Get virtual machine from command-line parameter
set vm = virtualServer.FindVirtualMachine(WScript.Arguments(0))

‘Save state the virtual machine
set saveTask = vm.Save

‘Loop waiting for task completion – and display status
while not saveTask.isComplete
WScript.Sleep 1000

‘Copy virtual hard disks and undo disks
for each vhd in vm.HardDiskConnections
objShell.Run “%comspec% /c copy ” & chr(34) & vhd.undoHardDisk.file & chr(34) & ” ” & chr(34) & WScript.Arguments(1) & chr(34),1 ,
objShell.Run “%comspec% /c copy ” & chr(34) & vhd.HardDisk.file & chr(34) & ” ” & chr(34) & WScript.Arguments(1) & chr(34),1 , True

‘Copy .VMC and .VSV files
objShell.Run “%comspec% /c copy ” & chr(34) & vm.File & chr(34) & ” ” & chr(34) & WScript.Arguments(1) & chr(34),1 , True
objShell.Run “%comspec% /c copy ” & chr(34) & vm.SavedStateFilePath & chr(34) & ” ” & chr(34) & WScript.Arguments(1) & chr(34),1 , True

‘Once everything is done – startup the virtual machine

‘Script ends

See – easy.  One interesting scripting note (which I could not find anywhere else) is that the “,1,True” option at the end of the objShell.Run command tells the vbScript to wait until after the command is completed – which is critical for this script.