次の方法で共有


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

Comments

  • Anonymous
    January 30, 2008
    The comment has been removed

  • Anonymous
    January 30, 2008
    > 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).

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

  • Anonymous
    January 30, 2008
    The comment has been removed

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

  • Anonymous
    December 16, 2011
    Thanks for a clear and simple script, it helped me!

  • Anonymous
    April 30, 2012
    Thanks for the simple and easy script... It worked for me

  • Anonymous
    May 29, 2012
    can this script be run from remote computer? rather than running locally on hyper-v host. than you

  • Anonymous
    August 16, 2012
    Hi, could you please help me get at least of the above scripts to work? Thanks