Reputation: 47
I am trying to apply a snapshot to a hyper V virtual machine using C# and using the 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
Upvotes: 2
Views: 365
Reputation: 323
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.
Upvotes: 1