How to 'delete' a virtual machine under Virtual Server

By default when you 'remove' a virtual machine under Virtual Server, none of the virtual machine files are deleted. Normally this is a good thing - but when you are trying to perform repetitive tests on a virtual machine it is annoying to have to delete the virtual machine files every time that you want to recreate it. So here is a handy (but dangerous) script that will unregister and delete a virtual machine and all its files:

'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))
vmcFile = vm.File

'Delete virtual hard disks and undo disks
for each vhd in vm.HardDiskConnections
objShell.Run "%windir%system32cmd /c del " & chr(34) & vhd.undoHardDisk.file & chr(34) & " /f"
objShell.Run "%windir%system32cmd /c del " & chr(34) & vhd.HardDisk.file & chr(34) & " /f"
next

'Delete saved state file
objShell.Run "%windir%system32cmd /c del " & chr(34) & vm.SavedStateFilePath & chr(34) & " /f"

'Unregister virtual machine
virtualServer.UnregisterVirtualMachine(vm)

'Delete virtual machine configuration file
objShell.Run "%windir%system32cmd /c del " & chr(34) & vmcFile & chr(34) & " /f"

'Script ends

Cheers,
Ben