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 = 其他。

已啟用 (2)

對應至 CIM_EnabledLogicalElement.EnabledState = Enabled。

已停用 (3)

對應至 CIM_EnabledLogicalElement.EnabledState = Disabled。

關閉 (4)

僅適用于 Hyper-V 第 1 版 (V1) 。 虛擬機器正透過關機服務關閉。 對應至 CIM_EnabledLogicalElement.EnabledState = ShuttingDown。

離線 (6)

對應至 CIM_EnabledLogicalElement.EnabledState = Enabled 但離線。

測試 (7)

延遲 (8)

停止 (9)

對應至 CIM_EnabledLogicalElement.EnabledState = Quiesce、Enabled 但已暫停。

重新開機 (10)

狀態從 [關閉 ] 或 [ 儲存執行中]。

重設 (11)

重設虛擬機器。 對應至 CIM_EnabledLogicalElement.EnabledState = Reset。

儲存 (32773)

在 Hyper-V 第 1 版 (V1) 中,對應至 EnabledStateSaving

暫停 (32776)

在 Hyper-V 第 1 版 (V1) 中,對應至 EnabledStatePausing

繼續 (32777)

在 Hyper-V 第 1 版 (V1) 中,對應至 EnabledStateResuming。 狀態從 [已暫停 ] 轉換為 [正在執行]。

FastSaved (32779)

對應至 EnabledStateFastSuspend

FastSaving (32780)

對應至 EnabledStateFastSuspending。 狀態從 執行 中轉換到 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

這個方法會傳回下列其中一個值。

傳回碼/值 Description
已完成,沒有錯誤
0
成功。
已檢查方法參數 - 已啟動轉換
4096
轉換是非同步。
拒絕存取
32769
拒絕存取。
32768
32770
32771
32772
32773
32774
此作業的狀態無效
32775
不支援 RequestedState 參數中指定的值。
32776
32777
32778

備註

Msvm_ComputerSystem 類別的 存取可能會受到 UAC 篩選的限制。 如需詳細資訊,請參閱 使用者帳戶控制和 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