Search code examples
c#parameterswmihyper-vmsdn

hyperv wmi How to pass a parameter as a string?


I use the newer Microsoft.Management.Infrastructure and I want to pass a parameter to the ModifySystemSettings method of the class Msvm_VirtualSystemManagementService:

https://learn.microsoft.com/en-us/windows/win32/hyperv_v2/modifysystemsettings-msvm-virtualsystemmanagementservice

The parameter type is a string that embedded an instance of the Msvm_VirtualSystemSettingData.

In the older version System.Management it is possible to use ManagementBaseObject.GetText(TextFormat.WmiDtd20) to convert it to string:

https://learn.microsoft.com/en-us/dotnet/api/system.management.managementbaseobject.gettext?view=netframework-4.8

The following code shows the current implementation of the ModifySystemSettings Method. Problem is that snapshotInstance.ToString() is obviously wrong. Does anyone know how to pass the parameter correctly?


CimInstance snapshotInstance = session.EnumerateAssociatedInstances(hvNamespace, vm, "Msvm_MostCurrentSnapshotInBranch", "Msvm_VirtualSystemSettingData", null, null).FirstOrDefault();

snapshotInstance.CimInstanceProperties["ElementName"].Value = "testSnapshot";
CimMethodParametersCollection modifySystemSettingsParameters = new CimMethodParametersCollection
{
     CimMethodParameter.Create("SystemSettings",snapshotInstance.ToString(),CimType.String, CimFlags.In)
       };

if(virtualSystemManagementService != null)
{
      CimMethodResult result = session.InvokeMethod(hvNamespace, virtualSystemManagementService, "ModifySystemSettings", modifySystemSettingsParameters);
      Console.WriteLine(result.ReturnValue.Value.ToString());
}

My goal is to change the name of a snapshot.


Solution

  • after some time I figured out the right solution.

    The CimSerializer helped me to convert it into a string.

    This is the code behind:

    CimSerializer serializer = CimSerializer.Create();
    byte[] serializedClass = serializer.Serialize(snapshotInstance, InstanceSerializationOptions.None);
    CimMethodParametersCollection modifySystemSettingsParameters = new CimMethodParametersCollection
    {
           CimMethodParameter.Create("SystemSettings",System.Text.Encoding.Unicode.GetString(serializedClass),CimType.String, CimFlags.In)
    };