Share via


Controlling Virtual Machines with a Script

I discovered how easy it is to control virtual machines with a script this weekend.  I have one server that I use to run virtual machines that I keep running all the time.  When I patch this server, I need to shut down all VMs before it is restarted and then restart the VMs after the computer starts.  After doing a quick search I discovered it only takes a few lines of code to shutdown or start a VM.

Shutdown a server named Server1
On Error Resume Next
Set objVS = CreateObject("VirtualServer.Application")
Set objVM = objVS.FindVirtualMachine("Server1")
Set objGuestOS = objVM.GuestOS
objGuestOS.Shutdown()

Startup a server named Server1
On Error Resume Next
Set objVS = CreateObject("VirtualServer.Application")
Set objVM = objVS.FindVirtualMachine("Server1")
objVM.Startup()

If you have multiple VMs you can put them all in the same script as shown below:

On Error Resume Next
Set objVS = CreateObject("VirtualServer.Application")
Set objVM = objVS.FindVirtualMachine("Server1")
Set objGuestOS = objVM.GuestOS
objGuestOS.Shutdown()
sleep 15000
Set objVS = CreateObject("VirtualServer.Application")
Set objVM = objVS.FindVirtualMachine("Server2")
Set objGuestOS = objVM.GuestOS
objGuestOS.Shutdown()

So to make things easier on me I wrote two simple scripts; one that starts the VMs and one that stops them.  I then configured a local policy on the server to run the script that starts the VMs as a "Startup Script" so the VMs would start automatically every time the server is started. 

Virtual Machine and Virtual Server Properties
https://www.microsoft.com/technet/scriptcenter/scripts/vs/default.mspx?mfr=true