简体   繁体   English

ApplySnapshot示例Hyper-V V2

[英]ApplySnapshot Example Hyper-V V2

I am trying to apply a snapshot to a hyper V virtual machine using C# and using the ApplySnapshot Method. 我正在尝试使用C#和ApplySnapshot方法将快照应用于Hyper V虚拟机。

ApplySnapshot method ApplySnapshot方法

But I seem to be struggling as there no sample class for that method. 但是我似乎很挣扎,因为该方法没有示例类。 I would be gratefull if someone could help in providing a sample or a sample project. 如果有人可以帮助提供示例或示例项目,我将不胜感激。

Many thanks 非常感谢

Billy 比利

This example will apply the most recent snapshot for a VM. 本示例将为VM应用最新快照。 This can easily be changed to apply a selected snapshot by replacing the 'lastSnapshot' with an instance of Msvm_VirtualSystemSettingData that represents the snapshot you would like to apply. 通过使用代表您要应用的快照的Msvm_VirtualSystemSettingData实例替换“ lastSnapshot”,可以轻松地将其更改为应用选定的快照。

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

Please let me know if you have any questions or run into any issues. 如果您有任何疑问或遇到任何问题,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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