Msvm_ComputerSystem 类的 RequestStateChange 方法

请求将虚拟机的状态更改为指定值。 多次调用 RequestStateChange 方法可能会导致早期请求被覆盖或丢失。 仅表示虚拟机的 Msvm_ComputerSystem 类的实例支持此方法。

状态更改正在进行时, RequestedState 属性将更改为 RequestedState 参数的值。

语法

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

参数

RequestedState [in]

类型: uint16

新状态。 大于 32767 的值是 DMTF 建议的值,可能会发生更改。

下面是可能的值:

其他 (1)

对应于 CIM_EnabledLogicalElement.EnabledState = Other。

已启用 (2)

对应于 CIM_EnabledLogicalElement.EnabledState = Enabled。

禁用 (3)

对应于 CIM_EnabledLogicalElement.EnabledState = Disabled。

关闭 (4)

仅在版本 1 (V1) Hyper-V 中有效。 虚拟机正在通过关闭服务关闭。 对应于 CIM_EnabledLogicalElement.EnabledState = ShuttingDown。

脱机 (6)

对应于 CIM_EnabledLogicalElement.EnabledState = 已启用但脱机。

测试 (7)

延迟 (8)

静止 (9)

对应于 CIM_EnabledLogicalElement.EnabledState = Quiesce,已启用但已暂停。

重新启动 (10)

状态从 “关闭”“保存” 转换为 “正在运行”。

重置 (11)

重置虚拟机。 对应于 CIM_EnabledLogicalElement.EnabledState = Reset。

保存 (32773)

在版本 1 (V1) Hyper-V 中,对应于 EnabledStateSaving

暂停 (32776)

在版本 1 (V1) Hyper-V 中,对应于 EnabledStatePausing

恢复 (32777)

在版本 1 (V1) Hyper-V 中,对应于 EnabledStateResuming。 状态从 “已暂停” 转换为 “正在运行”。

FastSaved (32779)

对应于 EnabledStateFastSuspend

FastSaving (32780)

对应于 EnabledStateFastSuspending。 状态从 Running 转换为 FastSaved

这些值表示关键状态:

RunningCritical (32781)

OffCritical (32782)

StoppingCritical (32783)

SavedCritical (32784)

PausedCritical (32785)

StartingCritical (32786)

ResetCritical (32787)

SavingCritical (32788)

暂停关键 (32789)

恢复关键 (32790)

FastSavedCritical (32791)

FastSavingCritical (32792)

作业 [out]

类型: CIM_ConcreteJob

Msvm_ConcreteJob 对象的可选引用,如果异步执行操作,则返回该对象。 如果存在,则返回的引用可用于监视进度并获取方法的结果。

TimeoutPeriod [in]

类型: datetime

未使用此参数。

返回值

类型: uint32

此方法返回以下值之一。

返回代码/值 说明
已完成,无错误
0
成功。
已选中方法参数 - 转换已启动
4096
转换是异步的。
拒绝访问
32769
访问被拒绝。
32768
32770
32771
32772
32773
32774
此操作的状态无效
32775
不支持 RequestedState 参数中指定的值。
32776
32777
32778

备注

UAC 筛选可能会限制对 Msvm_ComputerSystem 类的访问。 有关详细信息,请参阅 用户帐户控制和 WMI

示例

以下 C# 示例启动或禁用虚拟机。 可以在 V2) (虚拟化示例的常用实用工具 中找到引用的实用工具。

重要

若要正常运行,必须在虚拟机主机服务器上运行以下代码,并且必须使用管理员权限运行。

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]);
        }

    }
}

以下 Visual Basic Scripting Edition (VBScript) 示例启动或禁用虚拟机。

重要

若要正常运行,必须在虚拟机主机服务器上运行以下代码,并且必须使用管理员权限运行。

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

要求

要求
最低受支持的客户端
Windows 8 [仅限桌面应用]
最低受支持的服务器
Windows Server 2012 [仅限桌面应用]
命名空间
Root\Virtualization\V2
MOF
WindowsVirtualization.V2.mof
DLL
Vmms.exe

另请参阅

Msvm_ComputerSystem