简体   繁体   中英

Hyper-V RequestStateChange returns undocumented value

I'm attempting to programmatically start a Hyper-V VM using C#'s System.Management API. I've had great success creating and configuring the VM, however starting the VM has proven elusive.

I get a Msvm_ComputerSystem object, using a helper method to perform the WQL query:

ManagementObject compSys = WMIHelpers.GetMsvm_ComputerSystem(scope, vmName);

The method to change the VM state is (allegedly) "RequestStateChange" and I am able to get the parameters object and set them:

ManagementBaseObject callParams = compSys.GetMethodParameters("RequestStateChange");
callParams["RequestedState"] = WMIHelpers.RequestedState.Enabled;

However when I invoke the method, my return value is 1, which is undocumented:

ManagementBaseObject result = vsServ.InvokeMethod("RequestStateChange", callParams, null);

if(result["ReturnValue"] == 1)
{
    System.Console.WriteLine("WTF?!?");
}

I have no idea what I'm doing wrong here, or why I'm getting this undocumented return value.

I suggest reading the link below as I found this of great help when attempting to start a hyper-v from c#

http://msdn.microsoft.com/en-us/library/cc723874(v=vs.85).aspx

This question is a bit old, but I hit the same issue and found a solution.

For reference, articles in MSDN for WMIv1 are named cc______ and for WMIv2 are named hh______

WMIv1 WMIv2

The reason this error came up for me is because I created my VM through code and by default Msvm_ComputerSystem had a null value for AvailableRequestedStates. Subsequently when RequestStateChange is called, it returns back a 1, which is undocumented.

To fix this, populate Msvm_ComputerSystem with all of the available states before you call RequestStateChange:

UInt16[] availableRequestedStates = { 2, 3, 4, 6, 7, 8, 9, 10, 11 };
compSystem["AvailableRequestedStates"] = availableRequestedStates;
compSystem.Put();

ManagementBaseObject inParams = compSystem.GetMethodParameters("RequestStateChange");
inParams["RequestedState"] = 2;
ManagementBaseObject result = compSystem.InvokeMethod("RequestStateChange", inParams, null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM