Hyper-V How To: Change VM State using Script
Some friends here on the Hyper-V team shared a PowerShell 2.0 script for changing the VM state:
# Change state of VM
param(
[string]$vmName = $(throw "Must supply a virtual machine name")
[int]$newState = $(throw "Must specify a state to change to:`nEnabled: 2`nDisabled: 3`nReset: 10`nPaused: 32768`nSuspended: 32769`n"
)# Get the VM by name
$vm = gwmi -namespace root\virtualization Msvm_ComputerSystem -filter "ElementName='$vmName'"# Attempt to change state
$result = $vm.RequestStateChange($newState)if($result.ReturnValue -eq 4096){
# A Job was started, and can be tracked using its Msvm_Job instance
$job = [wmi]$result.Job
# Wait for job to finish
while($job.jobstate -lt 7){$job.get()}
# Return the Job's error code
return $job.ErrorCode
}
# Otherwise, the method completed
return $result.ReturnValue
For more info on how to use PS cmdlets see: https://www.microsoft.com/technet/scriptcenter/topics/msh/cmdlets/index.mspx
See also James O’Neil’s New and improved PowerShell Library for Hyper-V. Now with more functions and... documentation!
For all 35 sample Hyper-V PS1 scripts in a zipfile, go to: Hyper-V PowerShell Example Scripts.zip-download