Starting a Hyper-V Virtual Machine
Next in the line up of scripts - another simple one - starting a virtual machine:
VBScript:
Option Explicit
Dim WMIService
Dim VMList
Dim VMName
'Specify the name of the virtual machine that I want to start
VMName = "Windows Server 2003"
'Get instance of 'virtualization' WMI service on the local computer
Set WMIService = GetObject("winmgmts:\\.\root\virtualization")
'Query for the specific virtual machine that I want to start
Set VMList = WMIService.ExecQuery("SELECT * FROM Msvm_ComputerSystem WHERE ElementName='" & VMName & "'")
' Request a state change on the first VM that is returned
' 2 = start, 3 = stop and 32769 = save state
VMList.ItemIndex(0).RequestStateChange(2)
PowerShell:
#The name of the virtual machine to be started
$VMName = "Windows Server 2003"
#Get the VM Object
$query = "SELECT * FROM Msvm_ComputerSystem WHERE ElementName='" + $VMName + "'"
$VM = get-wmiobject -query $query -namespace "root\virtualization" -computername "."
#Request a state change on the VM
$Result = $VM.RequestStateChange(2)
Now for some notes:
Under VBScript a WMIService.ExecQuery will always return a collection, even if there is only one result. Using ItemIndex(0) allows you to assume that there is only one item in the collection and just act on it.
PowerShell will return a collection for multiple results, but an object if there is a single result. This can actually be a bit trickier to deal with if you have to handle both.
Since I am querying on the element name - it is actually possible to get multiple virtual machines back (you would need to have two virtual machines with the same name for this to happen). I am not handling this case here.
Cheers,
Ben