Scheduling task on Server 2008 – a Hyper-V snapshot

I had a mail from Alessandro, asking about scheduling operations on Hyper-V; specifically he wanted to schedule the snapshotting of a virtual machine. The logic was already in my codeplex library, but it only needs a couple of the functions (new-vmsnapshot and get-vm) , but the easiest thing seemed to be to make its own PS1 file and then create a scheduled job to run PowerShell with that command.

So here is the script which I saved in the Hyper-V program files folder as "New-VMSnapshot.ps1". It takes the name of a VM and optionally the name of a server and kicks off the snapshot.

 Param( $VMName , $Server=".")vm=Get-WmiObject -computername $Server -NameSpace "root\virtualization" `     -Query "Select * From MsVM_ComputerSystem Where ElementName Like '" + $VMName + "' AND Caption Like 'Virtual%' "if ($VM -is [System.Management.ManagementObject]) {     $arguments=($VM,$Null,$null)      $VSMgtSvc=Get-WmiObject -ComputerName $VM.__server -NameSpace "root\virtualization" `          -Class "MsVM_virtualSystemManagementService"     $result=$VSMgtSvc.psbase.invokeMethod("CreateVirtualSystemSnapshot",$arguments)}

Before explaining how to schedule the script, I should give a couple of warnings about snapshots: first, reverting a machine to a snapshot can break the connection to its domain because the password for the secure channel has changed since the snapshot was taken. In training, demo, or test environments you can shut everything down, make a consistent set of snapshots and apply them all. That's not an option for production environments.

Second, remember that a snapshot turns a VM's current disk into the parent half of a differencing disk, and if the VM is running saves its memory as well. You can use a lot of disk space by being over-eager with snapshots, and you will blunt system performance. Deleting snapshots merges the differencing disks (creating a temporary disk which uses even more space) but only when the machine is shut down. Restarting the VM before the merge is complete will abandon the operation. So if you schedule snapshots you should have a plan to remove them regularly.

Creating the scheduled task is easy on Server 2008 - it uses the same scheduling tools as Vista. go to the Task scheduler (either as a free-standing tool or in the server manage) right click the scheduler and choose add ask and click though the wizard. On the general page you need to make sure the task runs if no-one is logged on, the triggers page specifies when the task runs and the actions page specifies the command(s) ,

 %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe 

and arguments to be passed

 "& 'C:\Program Files\Hyper-V\new-Vmsnapshot.ps1' 'core' "

So much easier than the old AT commands.