Rename a snapshot in Hyper-V WMI V2 from C#

2019-08-21 05:44发布

I am trying to rename a Hyper-V snapshot (checkpoint) using root\virtualization\v2. None of the standard methods like ModifySystemSettings or ModifyVirtualSystem of Msvm_VirtualSystemSnapshotService or Msvm_VirtualSystemManagementService has been helpful so far.

Powershell Rename-VMSnapshot can do the job however I am not sure it is using WMI.

Any idea?

1条回答
该账号已被封号
2楼-- · 2019-08-21 06:22

Here is what worked for me:

//
// Rename last snapshot to desired name
//
using (ManagementBaseObject inParams = vmms.GetMethodParameters("ModifySystemSettings"))
{
    ManagementObject setting = null;

    ManagementObjectCollection settings = vm.GetRelated(
        "Msvm_VirtualSystemSettingData",
        "Msvm_MostCurrentSnapshotInBranch",
        null,
        null,
        "Dependent",
        "Antecedent",
        false,
        null
        );

    foreach (ManagementObject instance in settings)
    {
        // Usually only one, but loop through to the end to get latest one

        if (setting != null)
        {
            if (string.Compare(
                    (string)instance["CreationTime"],
                    (string)setting["CreationTime"],
                    true) > 0
                )
            {
                // Get latest one since there could be duplicates
                setting = instance;
            }
        }
        else
        {
            setting = instance;
        }
    }

    setting["ElementName"] = snapshotName;

    inParams["SystemSettings"] = setting.GetText(TextFormat.WmiDtd20);

    using (ManagementBaseObject outParams = vmms.InvokeMethod("ModifySystemSettings", inParams, null))
    {
        // What this does is get Job managementObject and check JobState to be JobCompleted.
        this.ProcessSnapshotMethodResult(outParams, "rename");
    }
}
查看更多
登录 后发表回答