Another script to backup a virtual machine

Last week I posted a sample script that would save state a virtual machine, make a copy of it, and restore it (details here:  While this is an effective solution – it can result in a significant window of ‘downtime’ if the virtual machine is large – as you have to wait for the entire virtual machine to be copied before restoring it from the saved state.

So today I am going to show you how to backup a virtual machine of any size with the only downtime being how long it takes to shutdown and restart the virtual machine.

The script below will shutdown a virtual machine (specified via command line argument) and then go through each of the virtual hard disks in the virtual machine and change them to newly created differencing disks.  Once this is done it then starts the virtual machine up again:

‘Script Begins

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

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

‘shutdown the virtual machine
set shutdownTask = vm.GuestOS.Shutdown

‘Loop waiting for task completion
while not shutdownTask.isComplete
   WScript.Sleep 1000

‘Merge undo disks if they exist
if vm.Undoable then

set mergeTask = vm.MergeUndoDisks

‘Loop waiting for task completion
while not mergeTask.isComplete
   WScript.Sleep 1000

end if

‘Create and hookup differencing disks
for each vhd in vm.HardDiskConnections
 newVhdName = Left(vhd.HardDisk.file, (len(vhd.HardDisk.file)-4)) & ” diff.vhd”
 set createTask = virtualServer.CreateDifferencingVirtualHardDisk(newVhdName , vhd.HardDisk.file)
 while not createTask.isComplete
  WScript.Sleep 1000
 set newVhdConn = vm.AddHardDiskConnection(newVhdName, vhd.busType, vhd.busNumber, vhd.deviceNumber)

‘Once everything is done – startup the virtual machine

‘Script ends

The advantage of this approach is that you can then copy away the base virtual hard disks at your leisure.  The downsides to this approach are that it only works for guest operating systems that have Virtual Machine Additions installed, and if you run this script repeatedly you are going to end up with a very long chain of differencing drives which can only be merged when the virtual machine is offline.