在C#的Hyper-V WMI V2中应用快照

时间:2013-11-18 22:20:49

标签: c# wmi hyper-v

我正在尝试在C#中复制以下PowerShell:

# Details from here are not particularly important but needed for full sample
$vms = gwmi -namespace "root\virtualization\v2" Msvm_ComputerSystem
$vm = $vms[3]
$snapshot = ($vm.GetRelated("Msvm_VirtualSystemSettingData") | Where { $_.ElementName -eq "SnapshotName" })[0]
# end unimportant 

$VMSS = Get-WMiObject -class Msvm_VirtualSystemSnapshotService -namespace root\virtualization\v2
$VMSS.ApplySnapshot($snapshot, $null)

此代码工作正常 - 快照按预期应用。

我在C#中获取Msvm_VirtualSystemSettingData实例或Msvm_VirtualSystemSnapshostService实例没有问题。但是,我似乎无法接听ApplySnapshot的权利 - 无论我给它什么,我都会InvalidOperationException。我正在使用Visual Studio生成的WMI代码进行调用:

public uint ApplySnapshot(ref System.Management.ManagementPath Job, System.Management.ManagementPath Snapshot) {
    if ((isEmbedded == false)) {
        System.Management.ManagementBaseObject inParams = null;
        inParams = PrivateLateBoundObject.GetMethodParameters("ApplySnapshot");
        // following line has been through variations as well with no change -
        // commenting it out, setting to null
        inParams["Job"] = ((System.Management.ManagementPath)(Job)).Path;
        inParams["Snapshot"] = ((System.Management.ManagementPath)(Snapshot)).Path;
        System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ApplySnapshot", inParams, null);
        Job = ((System.Management.ManagementPath)(outParams.Properties["Job"].Value));
        return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value);
    }
    else {
        return System.Convert.ToUInt32(0);
    }
}

我不确定要为Job参数传递什么,因为我们找回了一份工作 - 为ref而不是out提供null非常不寻常我已经尝试了很多不同的变体(包括将参数设置为inParams[Job]而不是设置它)没有运气。我也尝试将null设置为{{1}}而没有运气。

我应该做些什么来改变它?

1 个答案:

答案 0 :(得分:2)

我相信你的问题是,当你是一个出站参数时,你正在传递工作。该参数将从调用返回。像...这样的东西。

ManagementBaseObject inParams = null;

inParams = PrivateLateBoundObject.GetMethodParameters("ApplySnapshot");
inParams["Snapshot"] = ((System.Management.ManagementPath)(Snapshot)).Path;

ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ApplySnapshot", inParams, null);

// i left this as i assume this is vs generated though this isn't how i would normally
// get my jobs back.
Job = ((ManagementPath)(outParams.Properties["Job"].Value));

return Convert.ToUInt32(outParams.Properties["ReturnValue"].Value);
相关问题