RequestStateChange method of the Msvm_ComputerSystem class

Requests that the state of the virtual machine be changed to the specified value. Invoking the RequestStateChange method multiple times could result in earlier requests being overwritten or lost. This method is only supported for instances of the Msvm_ComputerSystem class that represent a virtual machine.

While the state change is in progress, the RequestedState property is changed to the value of the RequestedState parameter.

Syntax

uint32 RequestStateChange(
  [in]  uint16              RequestedState,
  [out] CIM_ConcreteJob REF Job,
  [in]  datetime            TimeoutPeriod
);

Parameters

RequestedState [in]

Type: uint16

The new state. Values that are greater than 32767 are DMTF proposed values and are subject to change.

Here are possible values:

Other (1)

Corresponds to CIM_EnabledLogicalElement.EnabledState = Other.

Enabled (2)

Corresponds to CIM_EnabledLogicalElement.EnabledState = Enabled.

Disabled (3)

Corresponds to CIM_EnabledLogicalElement.EnabledState = Disabled.

Shut Down (4)

Valid in version 1 (V1) of Hyper-V only. The virtual machine is shutting down via the shutdown service. Corresponds to CIM_EnabledLogicalElement.EnabledState = ShuttingDown.

Offline (6)

Corresponds to CIM_EnabledLogicalElement.EnabledState = Enabled but offline.

Test (7)

Defer (8)

Quiesce (9)

Corresponds to CIM_EnabledLogicalElement.EnabledState = Quiesce, Enabled but paused.

Reboot (10)

State transition from Off or Saved to Running.

Reset (11)

Reset the virtual machine. Corresponds to CIM_EnabledLogicalElement.EnabledState = Reset.

Saving (32773)

In version 1 (V1) of Hyper-V, corresponds to EnabledStateSaving.

Pausing (32776)

In version 1 (V1) of Hyper-V, corresponds to EnabledStatePausing.

Resuming (32777)

In version 1 (V1) of Hyper-V, corresponds to EnabledStateResuming. State transition from Paused to Running.

FastSaved (32779)

Corresponds to EnabledStateFastSuspend.

FastSaving (32780)

Corresponds to EnabledStateFastSuspending. State transition from Running to FastSaved.

These values represent critical states:

RunningCritical (32781)

OffCritical (32782)

StoppingCritical (32783)

SavedCritical (32784)

PausedCritical (32785)

StartingCritical (32786)

ResetCritical (32787)

SavingCritical (32788)

PausingCritical (32789)

ResumingCritical (32790)

FastSavedCritical (32791)

FastSavingCritical (32792)

Job [out]

Type: CIM_ConcreteJob

An optional reference to a Msvm_ConcreteJob object that is returned if the operation is executed asynchronously. If present, the returned reference can be used to monitor progress and obtain the result of the method.

TimeoutPeriod [in]

Type: datetime

This parameter is not used.

Return value

Type: uint32

This method returns one of the following values.

Return code/value Description
Completed with No Error
0
Success.
Method Parameters Checked - Transition Started
4096
The transition is asynchronous.
Access Denied
32769
Access denied.
32768
32770
32771
32772
32773
32774
Invalid state for this operation
32775
The value specified in the RequestedState parameter is not supported.
32776
32777
32778

Remarks

Access to the Msvm_ComputerSystem class might be restricted by UAC Filtering. For more information, see User Account Control and WMI.

Examples

The following C# example starts or disables a virtual machine. The referenced utilities can be found in Common utilities for the virtualization samples (V2).

Important

To function correctly, the following code must be run on the virtual machine host server, and must be run with administrator privileges.

using System;
using System.Management;

namespace HyperVSamples
{
    public class RequestStateChangeClass
    {
        public static void RequestStateChange(string vmName, string action)
        {
            ManagementScope scope = new ManagementScope(@"\\.\root\virtualization\v2", null);
            ManagementObject vm = Utility.GetTargetComputer(vmName, scope);

            if (null == vm)
            {
                throw new ArgumentException(
                    string.Format(
                    "The virtual machine '{0}' could not be found.", 
                    vmName));
            }

            ManagementBaseObject inParams = vm.GetMethodParameters("RequestStateChange");

            const int Enabled = 2;
            const int Disabled = 3;

            if (action.ToLower() == "start")
            {
                inParams["RequestedState"] = Enabled;
            }
            else if (action.ToLower() == "stop")
            {
                inParams["RequestedState"] = Disabled;
            }
            else
            {
                throw new Exception("Wrong action is specified");
            }

            ManagementBaseObject outParams = vm.InvokeMethod(
                "RequestStateChange", 
                inParams, 
                null);

            if ((UInt32)outParams["ReturnValue"] == ReturnCode.Started)
            {
                if (Utility.JobCompleted(outParams, scope))
                {
                    Console.WriteLine(
                        "{0} state was changed successfully.", 
                        vmName);
                }
                else
                {
                    Console.WriteLine("Failed to change virtual system state");
                }
            }
            else if ((UInt32)outParams["ReturnValue"] == ReturnCode.Completed)
            {
                Console.WriteLine(
                    "{0} state was changed successfully.", 
                    vmName);
            }
            else
            {
                Console.WriteLine(
                    "Change virtual system state failed with error {0}", 
                    outParams["ReturnValue"]);
            }

        }

        public static void Main(string[] args)
        {
            if (args != null && args.Length != 2)
            {
                Console.WriteLine("Usage: <application> vmName action");
                Console.WriteLine("action: start|stop");
                return;
            }

            RequestStateChange(args[0], args[1]);
        }

    }
}

The following Visual Basic Scripting Edition (VBScript) example starts or disables a virtual machine.

Important

To function correctly, the following code must be run on the virtual machine host server, and must be run with administrator privileges.

dim objWMIService
dim fileSystem

const JobStarting = 3
const JobRunning = 4
const JobCompleted = 7
const wmiStarted = 4096
const Enabled = 2
const Disabled = 3



Main()

'-----------------------------------------------------------------
' Main routine
'-----------------------------------------------------------------
Sub Main()
    set fileSystem = Wscript.CreateObject("Scripting.FileSystemObject")

    strComputer = "."
    set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\virtualization\v2")

    set objArgs = WScript.Arguments
    if WScript.Arguments.Count = 2 then
       vmName= objArgs.Unnamed.Item(0)
       action = objArgs.Unnamed.Item(1)
    else
       WScript.Echo "usage: cscript StartVM.vbs vmName start|stop"
       WScript.Quit
    end if
    
    set computerSystem = GetComputerSystem(vmName)

    if RequestStateChange(computerSystem, action) then

        WriteLog "Done"
        WScript.Quit(0)
    else
        WriteLog "RequestStateChange failed"
        WScript.Quit(1)
    end if

End Sub

'-----------------------------------------------------------------
' Retrieve Msvm_VirtualComputerSystem from base on its ElementName
' 
'-----------------------------------------------------------------
Function GetComputerSystem(vmElementName)
    On Error Resume Next
    query = Format1("select * from Msvm_ComputerSystem where ElementName = '{0}'", vmElementName)
    set GetComputerSystem = objWMIService.ExecQuery(query).ItemIndex(0)
    if (Err.Number <> 0) then
        WriteLog Format1("Err.Number: {0}", Err.Number)
        WriteLog Format1("Err.Description:{0}",Err.Description)
        WScript.Quit(1)
    end if
End Function


'-----------------------------------------------------------------
' Turn on a virtual machine
'-----------------------------------------------------------------
Function RequestStateChange(computerSystem, action)
    WriteLog Format2("RequestStateChange({0}, {1})", computerSystem.ElementName, action)

    RequestStateChange = false
    set objInParam = computerSystem.Methods_("RequestStateChange").InParameters.SpawnInstance_()
    
    if action = "start" then
        objInParam.RequestedState = Enabled
    else
        objInParam.RequestedState = Disabled
    end if

    set objOutParams = computerSystem.ExecMethod_("RequestStateChange", objInParam)

    if (WMIMethodStarted(objOutParams)) then
        if (WMIJobCompleted(objOutParams)) then
            WriteLog Format1("VM {0} was started successfully", computerSystem.ElementName)
            RequestStateChange = true
        end if
    end if

End Function


'-----------------------------------------------------------------
' Handle wmi return values
'-----------------------------------------------------------------
Function WMIMethodStarted(outParam)

    WMIMethodStarted = false

    if Not IsNull(outParam) then
        wmiStatus = outParam.ReturnValue

        if  wmiStatus = wmiStarted then
            WMIMethodStarted = true
        end if

    end if

End Function


'-----------------------------------------------------------------
' Handle wmi Job object
'-----------------------------------------------------------------
Function WMIJobCompleted(outParam)
    dim WMIJob

    set WMIJob = objWMIService.Get(outParam.Job)

    WMIJobCompleted = true

    jobState = WMIJob.JobState

    while jobState = JobRunning or jobState = JobStarting

        WScript.Sleep(1000)
        set WMIJob = objWMIService.Get(outParam.Job)
        jobState = WMIJob.JobState

    wend


    if (jobState <> JobCompleted) then
        WriteLog Format1("ErrorDescription:{0}", WMIJob.ErrorDescription)
        WMIJobCompleted = false
    end if

End Function

'-----------------------------------------------------------------
' Create the console log files.
'-----------------------------------------------------------------
Sub WriteLog(line)
    dim fileStream
    set fileStream = fileSystem.OpenTextFile(".\StartVM.log", 8, true)
    WScript.Echo line
    fileStream.WriteLine line
    fileStream.Close

End Sub


'------------------------------------------------------------------------------
' The string formatting functions to avoid string concatenation.
'------------------------------------------------------------------------------
Function Format2(myString, arg0, arg1)
    Format2 = Format1(myString, arg0)
    Format2 = Replace(Format2, "{1}", arg1)
End Function

'------------------------------------------------------------------------------
' The string formatting functions to avoid string concatenation.
'------------------------------------------------------------------------------
Function Format1(myString, arg0)
    Format1 = Replace(myString, "{0}", arg0)
End Function

Requirements

Requirement Value
Minimum supported client
Windows 8 [desktop apps only]
Minimum supported server
Windows Server 2012 [desktop apps only]
Namespace
Root\Virtualization\V2
MOF
WindowsVirtualization.V2.mof
DLL
Vmms.exe

See also

Msvm_ComputerSystem