Starting a Hyper-V Virtual Machine

Starting a Hyper-V Virtual Machine

  • Comments 9

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

Leave a Comment
  • Please add 8 and 7 and type the answer here:
  • Post
  • How do we actually create one from scratch then?

    Looking around the WMI methods but cant find anything obvious!

  • > 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.

    Use of @(values) can mitigate this... forces an array to be created (even if zero or one elements long).

  • Would appreciate .Net samples as well (VB, C#) as it is trickier with strongly types languages.

  • Andreas - that is quite tricky.  I will get to it eventually.

    Richard - thanks for the tip!

    Joe - Yes, this is coming.

    Cheers,

    Ben

  • Thanks, I had no HyperV manager available so this helped me out alot!

  • Thanks for a clear and simple script, it helped me!

  • Thanks for the simple and easy script... It worked for me

  • can this script be run from remote computer? rather than running locally on hyper-v host.

    than you

  • Hi,

    could you please help me get at least of the above scripts to work?

    Thanks

Page 1 of 1 (9 items)