Reputation: 4780
I am trying to create a VM in Hyper-V with WMI.
ManagementClass virtualSystemManagementService =
new ManagementClass(@"root\virtualization\v2:Msvm_VirtualSystemManagementService");
ManagementBaseObject inParams =
virtualSystemManagementService
.GetMethodParameters("DefineSystem");
// Add the input parameters.
ManagementClass virtualSystemSettingData =
new ManagementClass(@"root\virtualization\v2:Msvm_VirtualSystemSettingData")
{
["ElementName"] = "Test"
};
inParams["SystemSettings"] =
virtualSystemSettingData.GetText(TextFormat.CimDtd20);
// Execute the method and obtain the return values.
ManagementBaseObject outParams =
virtualSystemManagementService
.InvokeMethod("DefineSystem", inParams, null);
The call to InvokeMethod throws an System.Management.MangementException - "Invalid method Parameter(s).
I am basing this code on https://blogs.msdn.microsoft.com/virtual_pc_guy/2013/06/20/creating-a-virtual-machine-with-wmi-v2/
I do realize that this is really easy with powershell, but I am trying to understand how the WMI side of things works.
Upvotes: 0
Views: 1962
Reputation: 488
Basic workflow For Virtual Machine Creation using WMI with C#:
You missed creating an instance of VirtualSystemSettingData and getting an instance of VirtualSystemManagment Service. The exception System.Management.MangementException - "Invalid method Parameter(s) is thrown when you call invoke method on a class not an object!
Example:
ManagementClass virtualSystemManagementServiceClass =
new ManagementClass(@"root\virtualization\v2:Msvm_VirtualSystemManagementService");
ManagementBaseObject inParams =
virtualSystemManagementServiceClass
.GetMethodParameters("DefineSystem");
// Add the input parameters.
ManagementClass virtualSystemSettingDataClass =
new ManagementClass(@"root\virtualization\v2:Msvm_VirtualSystemSettingData")
{
["ElementName"] = "Test"
};
// Create Instance of VirtualSystemSettingData
ManagementObject virtualSystemSettingData = virtualSystemSettingDataClass.CreateInstance();
inParams["SystemSettings"] =
virtualSystemSettingData.GetText(TextFormat.CimDtd20);
// Get Instance of VirtualSystemManagmentService
ManagementObject virtualSystemManagementService = null;
foreach (ManagementObject instance in virtualSystemManagementServiceClass.GetInstances())
{
virtualSystemManagementService = instance;
break;
}
// Execute the method and obtain the return values.
ManagementBaseObject outParams = virtualSystemManagementService.InvokeMethod("DefineSystem", inParams, null);
Upvotes: 1
Reputation: 194
You need to create an instance of msvm_VirtualSystemSettingData.
ManagementObject newInstance = new ManagementClass(scope, new ManagementPath("Msvm_VirtualSystemSettingData"), null).CreateInstance();
newInstance["ElementName"] = vmName;
inParameters["SystemSettings"] = newInstance.GetText(TextFormat.CimDtd20);
Upvotes: 0