Programmable Add VHD to Remote Hyper-V Virtual Machine

Using Hyper-V Manager, I can connect to the remote VM node, go to the virtual machine settings and add the existing .VHD file as a new hard drive. If the 2008 R2 server is running on the VM host and the drive connects to the SCSI controller, I can do this even while the virtual machine is running (see What's New in Hyper-V R2 ).

By doing this manually, everything works fine. The problem is that now I want to automate it so that I can attach various VHDs on the fly during some automated tests.

I already have C # code that connects to the remote VM host via WMI and starts / stops the virtual machines by calling RequestStateChange , and I would like to extend it in order to be able to say "here is the path to VHD, attach it as a SCSI disk to this virtual machine. " But looking at the list of WMI virtualization classes , I cannot figure out how to do this.

The closest I found is the Mount method of Msvm_ImageManagementService , but it looks like it mounts VHD inside the current OS, which I don't want.

+4
source share
2 answers

You must add a synthetic disk (ResourceType. Disk , ResourceSubType. DiskSynthetic ) using Msvm_VirtualSystemManagementService.AddVirtualSystemResources. Parent = WMI path of the SCSI controller.

ManagementObject synthetic = Utilities.GetResourceAllocationSettingData(scope, ResourceType.Disk, ResourceSubType.DiskSynthetic); synthetic["Parent"] = <ideControllerPath>; //or SCSI controller path (WMI path) synthetic["Address"] = <diskDriveAddress>; //0 or 1 for IDE string[] RASDs = new string[1]; RASDs[0] = synthetic.GetText(TextFormat.CimDtd20); 

Then attach the virtual hard drive (ResourceType. StorageExtent , ResourceSubType. VHD ) using Msvm_VirtualSystemManagementService.AddVirtualSystemResources. Parent = WMI path to the synthetic disk, Connection = * .vhd file path.

 ManagementObject hardDisk = Utilities.GetResourceAllocationSettingData(scope, ResourceType.StorageExtent, ResourceSubType.VHD); hardDisk["Parent"] = <syntheticPath>; //WMI path string[] connection = { <vhdPath> }; //Path to *.vhd file hardDisk["Connection"] = connection; string[] RASDs = new string[1]; RASDs[0] = hardDisk.GetText(TextFormat.CimDtd20); 

Use Common Utilities for Virtualization Samples and WMI Explorer .

+4
source

Also look at http://hypervlib.codeplex.com for an example.

+2
source

Source: https://habr.com/ru/post/1300470/


All Articles