我正在使用 C# 程序创建 Hyper-V 快照:
private static bool Snapshot(string vmName, string snapshotName)
{
var result = false;
var scope = new ManagementScope(@"root\virtualization", null);
var virtualSystemService = Utility.GetServiceObject(scope, "Msvm_VirtualSystemManagementService");
var vm = Utility.GetTargetComputer(vmName, scope);
var inParams = virtualSystemService.GetMethodParameters("CreateVirtualSystemSnapshot");
inParams["SourceSystem"] = vm.Path.Path;
var outParams = virtualSystemService.InvokeMethod("CreateVirtualSystemSnapshot", inParams, null);
if ((UInt32)outParams["ReturnValue"] == ReturnCode.Started)
{
if (Utility.JobCompleted(outParams, scope))
{
Console.WriteLine("Snapshot was created successfully.");
result = true;
}
else
{
Console.WriteLine("Failed to create snapshot VM");
result = false;
}
}
else if ((UInt32)outParams["ReturnValue"] == ReturnCode.Completed)
{
Console.WriteLine("Snapshot was created successfully.");
result = true;
}
else
{
Console.WriteLine("Create virtual system snapshot failed with error {0}", outParams["ReturnValue"]);
result = false;
}
inParams.Dispose();
outParams.Dispose();
vm.Dispose();
virtualSystemService.Dispose();
return result;
}
(注意:此代码取自MSDN)
有没有办法通过这个 WMI 调用设置快照名称?否则,有没有人知道通过 WMI 调用重命名快照的可行解决方案?我已经找到了这个线程,但它有点模棱两可,它没有提供任何解决方案......
编辑:解决方案是在创建快照后重命名它。这是我使用 Hans 建议重命名快照的函数:
解决方案:
public static bool RenameSnapshot(string vmName, string snapshotName)
{
var result = false;
var scope = new ManagementScope(@"root\virtualization", null);
var vm = Utility.GetTargetComputer(vmName, scope);
// load snapshot
var objSnapshot = GetLastVirtualSystemSnapshot(vm);
// rename snapshot
objSnapshot["ElementName"] = snapshotName;
// save
var virtualSystemService = Utility.GetServiceObject(scope, "Msvm_VirtualSystemManagementService");
var inParams = virtualSystemService.GetMethodParameters("ModifyVirtualSystem");
inParams["ComputerSystem"] = vm.Path.Path;
inParams["SystemSettingData"] = objSnapshot.GetText(TextFormat.CimDtd20);
var outParams = virtualSystemService.InvokeMethod("ModifyVirtualSystem", inParams, null);
if ((UInt32)outParams["ReturnValue"] == ReturnCode.Completed)
{
result = true;
}
else
{
result = false;
}
inParams.Dispose();
outParams.Dispose();
vm.Dispose();
virtualSystemService.Dispose();
return result;
}