Suspend Hyper-V VMs with PowerShell

I have one Hyper-V R2 server that fights with me on occasion. The VMs are responsive and I can RDP into them. The server itself is sometimes responsive, and I can RDP into it, but it fails to connect to Hyper-V manager. A reboot usually clears up the problem, but I hate to reboot the host machine with VMs still running.

I have noticed, however, that I can still access Hyper-V through the PowerShell API. As the VMs on this machine aren’t critical, I can suspend the VMs using the API. Then I can reboot the host machine, and start the VMs back up again using Hyper-V manager.

Here is the script I’ve been using to do this:

$State = @{‘Enabled’ = 2 ; ‘Disabled’= 3;  ‘Paused’= 32768 ; ‘Suspended’ = 32769 ; ‘Starting’ = 32770 ; ‘Snapshotting’ = 32771 ; ‘Migrating’ = 32772 ; ‘Saving’ = 32773 ; ‘Stopping’ = 32774 ; ‘Deleted’ = 32775 ; ‘Pausing’ = 32776 } 

$ListofVMs = get-wmiobject -namespace root\virtualization Msvm_ComputerSystem 

foreach ($VM in $ListOfVMs) 
    write-host -foreground yellow "Saving state VM $($VM.ElementName) now"

It will loop through all of the VMs on the host machine and suspend them if they are running. You could also replace $State[‘Suspended’] with a different state if you wanted perform a different action.


One thought on “Suspend Hyper-V VMs with PowerShell

Comments are closed.