简体   繁体   中英

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.

ApplySnapshot method

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. 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.

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.

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