Bring on the Scripts!

Okay! Now that initial documentation of the Hyper-V WMI API is available I thought I would respond with a "Week of Hyper-V Scripts".

Starting with a simple one - here is a script that will list the name, identifier and state for each virtual machine on the physical computer:

VBScript:

 Option Explicit
  
 Dim WMIService
 Dim VMList
 Dim VM
  
 'Get instance of 'virtualization' WMI service on the local computer
 Set WMIService = GetObject("winmgmts:\\.\root\virtualization")
  
 'Get all the MSVM_ComputerSystem object
 Set VMList = WMIService.ExecQuery("SELECT * FROM Msvm_ComputerSystem")
     
 For Each VM In VMList
    if VM.Caption = "Microsoft Virtual Computer System" then
        WScript.Echo "========================================"
        WScript.Echo "VM Name: " & VM.ElementName
        WScript.Echo "VM GUID: " & VM.Name
        WScript.Echo "VM State: " & VM.EnabledState
     end if
 Next

PowerShell:

 # Get all VM objects on the local computer
 $VMs = gwmi -class "MSVM_ComputerSystem" -namespace "root\virtualization" -computername "."
  
 foreach ($VM in $VMs){
    if ($VM.Caption -match "Microsoft Virtual Computer System"){
       write-host "=================================="
       write-host "VM Name:  " $VM.ElementName
       write-host "VM GUID:  " $VM.Name
       write-host "VM State: " $VM.EnabledState
    }
 }

Now to pull these scripts apart a bit:

  • The flow of these scripts is:

    • Get WMI Service object for virtualization namespace
    • Execute WMI query to get all VM objects
    • Iterate over the VM objects
  • For each virtual machine object we display the "ElementName" - which is the friendly name that you give the virtual machine ("Windows Server Foo") - the "Name" - which is a GUID that is used to internally uniquely identify the virtual machine and the "EnabledState" (you can find what the different EnabledState values mean here: https://msdn2.microsoft.com/en-us/library/cc136822(VS.85).aspx).

  • "gwmi" is PowerShell shorthand for "Get-WMIObject"

  • Amusingly enough this script would also return information about the parent partition (which is technically a virtual machine) which is why I check the caption of the virtual machine and only display information about entries that are actually virtual machines.

Cheers,

Ben