ApplySnapshot示例Hyper-V V2

时间:2015-09-10 12:03:47

标签: c# hyper-v wmi-query

我正在尝试使用C#并使用ApplySnapshot方法将快照应用于超V虚拟机。

ApplySnapshot method

但我似乎很挣扎,因为那个方法没有样本类。如果有人可以帮助提供样品或样品项目,我将不胜感激。

非常感谢

比利

1 个答案:

答案 0 :(得分:0)

此示例将应用VM的最新快照。通过将“lastSnapshot”替换为表示要应用的快照的Msvm_VirtualSystemSettingData实例,可以轻松更改此选项以应用选定的快照。

public static class VirtualSystemSnapshot
{
    public static object Revert(VirtualMachine vm)
    {
        ManagementScope scope = new ManagementScope("\\\\" + ServerName + "\\Root\\Virtualization\\V2", Options);
        using (ManagementObject virtualMachine = WmiUtilities.GetVirtualMachine(vmElementName, scope)) {
            using (ManagementObject virtualSystemSettingData = WmiUtilities.GetVirtualSystemSettingData(scope, virtualMachine)) {
                using (ManagementObject virtualSystemSnapshotService = WmiUtilities.GetVirtualSystemSnapshotService(scope)) {
                    using (ManagementObject lastSnapshot = WmiUtilities.GetFirstObjectFromCollection(virtualSystemSettingData.GetRelated("Msvm_VirtualSystemSettingData", "Msvm_ParentChildSettingData", null, null, null, null, false, null))) {
                        using (ManagementBaseObject inParams = virtualSystemSnapshotService.GetMethodParameters("ApplySnapshot")) {
                            inParams("Snapshot") = lastSnapshot;

                            // In order to apply a snapshot, the virtual machine must first be saved
                            RequestStateChange.Main(vm, RequestStateChange.RequestedState.Save, false);

                            using (ManagementBaseObject outParams = virtualSystemSnapshotService.InvokeMethod("ApplySnapshot", inParams, null)) {
                                WmiUtilities.ValidateOutput(outParams, scope);

                                // Now that the snapshot has been applied, start the VM back up
                                RequestStateChange.Main(vm, RequestStateChange.RequestedState.Start, false);
                            }
                        }
                    }
                }
            }
        }
    }
}

如果您有任何疑问或遇到任何问题,请与我们联系。