Share via


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 = 사용하지만 오프라인에 해당합니다.

테스트 (7)

연기 (8)

정지 (9)

CIM_EnabledLogicalElement.EnabledState = 정지, 사용되었지만 일시 중지됨에 해당합니다.

다시 부팅 (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)

PausingCritical (32789)

ResumingCritical (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

설명

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

    }
}

다음 VBScript(Visual Basic Scripting Edition) 예제에서는 가상 머신을 시작하거나 사용하지 않도록 설정합니다.

중요

올바르게 작동하려면 다음 코드를 가상 머신 호스트 서버에서 실행해야 하며 관리자 권한으로 실행해야 합니다.

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