Hyper-V, PowerShell, and WMI

Let's use this article to provide quick Hyper-V tasks in PowerShell.

Get a list of virtual machines on a Hyper-V parent


      # This can be run locally     or  against a remote parent. Use "."  for local  
      $VMs = gwmi MSVM_ComputerSystem -computer "<computername>" -namespace "root\virtualization" 
      ForEach (    $vm in $VMs) {  
                   if ($vm.name -ne $vm.elementname) {    #skip the parent's name    
                        $vm      .elementname        
                   }        
      }  

From the above, we can see that the list of $VMs is a list of objects. To get an object for an individual VM, we can go use:
$vm = Get-WMIObject MSVM_ComputerSystem -namespace root\virtualization -filter "ElementName = 'vmname' "

To start a VM we need to change its EnabledState to "2". So:


      $vmName = $args[0]  
      if (! $vmName  ) {  
                   $vmName = read-host "Which Virtual Machine do you wish to start? "    
      }     
      $vm = gwmi -namespace root\virtualization Msvm_ComputerSystem -filter "ElementName='$vmName' " 
      if ( $vm.EnabledState -eq 2 ) {  
                  write-host       "The virtual machine $vmName is already running."   
      }     else  {   
                  $vm      .RequestStateChange(2)        
      }    

Shutdown a single virtual machine on the local parent

# Shutdown a virtual machine. Based on initial idea from Tony Soper.     
# Expects a VM name as  an argument, or  prompts for  the name.  
    
$vmName = $args[0]  
if (! $vmName  ) {  
   $vmName = read-host "Which Virtual Machine do you wish to shut down?"  
}   
write-host "Shutting down $vm for system maintenance"  
# Get the VM by name and  request state to change to Enabled   
$vm = gwmi -namespace root\virtualization Msvm_ComputerSystem -filter "ElementName='$vmName'"   
     
# Get the associated Shutdown Component   
$shutdown = gwmi -namespace root\virtualization  -query  "Associators of {$vm} where ResultClass=Msvm_ShutdownComponent"   
     
if (! $shutdown ) {  
   write-host "Virtual machine $vmName is already shut down."  
} else  {      
# Initiate a forced shutdown with simple reason string, return  resulting error code   
return $shutdown.InitiateShutdown($true,"System Maintenance")   
} 

To Create a VHD:
$vhdsvc =  gwmi -class "Msvm_ImageManagementService" -name root\virtualization
$DynVHD = $vhdsvc.CreateDynamicVirtualHardDisk("E:\Test\Test-Sys.vhd", 120GB)    #Create 120Gb Dynamic VHD
$FixedVHD = $vhdsvc.CreateFixedVirtualHardDisk("E:\Test\Test-Data.vhd",40GB)  #Create 40GB Fixed VHD
$vhdJob = [wmi]$FixedVHD.job        # Job Status for creating the VHD

For more Hyper-V powerShell scripts, such as List virtual machines in a hyper-v host cluster Seehttp://social.technet.microsoft.com/wiki/contents/articles/hyper-v-scripts.aspx

A really useful module for use with Hyper-V and PowerShell is on CodePlex at: http://pshyperv.codeplex.com/


See Also