My goal is to programmatically create a new Virtual machine and attach an exisiting vhdx file to that machine. The only inputs to my program are the VM name and VHDX path. I'm implementing this using Hyper-V WMI Provider and Virtualization V2 namespace. Basically I'm implementing what is given in this article as a script. As mentioned in this link, I first add a synthetic drive and then try to attach the vhdx file.
I'm able to successfully create a Virtual Machine and add a synthetic drive to the machine. However, when I try to add the hard disk vhdx file, I'm getting the below error.
'New Virtaul Machine' failed to add resources.(Virtual machine ID ...).
The job error code is 32768 and the job state is 10 which just corresponds to 'Failed'.
This is the code that I use to connect the vhdx file.
//Add VHD
ManagementObject^ hardDisk = GetResourceAllocationsettingDataDefault(scope, 31, "Microsoft:Hyper-V:Virtual Hard Disk", "-");
hardDisk = (ManagementObject^)hardDisk->Clone();
array<String^>^ connection = gcnew array<String^>(1);
connection[0]="E:\\test.vhdx"; //Path to *.vhd file
hardDisk["Parent"] = synthetic->Path->Path; //WMI path-> This is the path of the synthetic drive that I added in the previous step.
hardDisk["HostResource"] = connection;
array<String^> ^ HDs = gcnew array<String^>(1);
HDs[0] = hardDisk->GetText(TextFormat::WmiDtd20);
ManagementBaseObject^ VHDinParams = vmtoCreate->GetMethodParameters("AddResourceSettings");
VHDinParams["AffectedConfiguration"] = settings->Path->Path;
VHDinParams["ResourceSettings"] = HDs;
ManagementBaseObject^ VHDoutParams = vmtoCreate->InvokeMethod("AddResourceSettings", VHDinParams, nullptr);
For the method GetResourceAllocationsettingDataDefault, refer this link. When I analyze VHDoutParams variable for error message and error code, I just get the below details.
Error description: 'New Virtaul Machine' failed to add resources.(Virtual machine ID ...).
Error Code: 32768(Failed)
Job State: 10
I don't know what I am missing. I am running the program in elevated mode as administrator. I don't have antivirus installed in the Hyper-V host machine.I have also searched the Internet thoroughly but couldn't find anything of help. What am I missing or doing wrong?