问题
Using Hyper-V Manager, I can connect to a remote VM host, go to the settings of a VM, and add an existing .VHD file as a new hard disk. If the VM host is running Server 2008 R2, and the disk is being attached to a SCSI controller, I can even do this while the VM is running (see What's new in Hyper-V R2).
Doing this manually, everything works great. The trouble is, now I want to automate it so I can attach different VHDs on-the-fly during some automated tests.
I already have C# code that connects to the remote VM host over WMI and starts/stops VMs by calling RequestStateChange, and I'd like to extend it to be able to say "here's the path to a VHD, attach it as a SCSI drive to this VM". But looking at the list of WMI virtualization classes, I can't figure out how to do this.
The closest I've found is the Mount method of Msvm_ImageManagementService, but this appears to mount a VHD inside the current OS, which isn't what I want.
回答1:
It is necessary to add synthetic disk (ResourceType.Disk, ResourceSubType.DiskSynthetic) using Msvm_VirtualSystemManagementService.AddVirtualSystemResources. Parent = SCSI controller's WMI path.
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 to attach virtual hard disk (ResourceType.StorageExtent, ResourceSubType.VHD) using Msvm_VirtualSystemManagementService.AddVirtualSystemResources. Parent = Synthetic disk's WMI path, 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 the Virtualization Samples and WMI Explorer.
回答2:
Also take a look at http://hypervlib.codeplex.com for an example.
来源:https://stackoverflow.com/questions/2210288/programmatically-attaching-a-vhd-to-a-remote-hyper-v-vm