以编程方式将VHD附加到远程Hyper-V VM

时间:2010-02-05 20:44:26

标签: c# hyper-v windows-server-2008-r2 vhd

使用Hyper-V Manager,我可以连接到远程VM主机,转到VM的设置,并将现有的.VHD文件添加为新硬盘。如果VM主机正在运行Server 2008 R2,并且磁盘正在连接到SCSI控制器,我甚至可以在VM运行时执行此操作(请参阅What's new in Hyper-V R2)。

手动执行此操作,一切都很顺利。问题是,现在我想自动化它,这样我就可以在一些自动化测试中即时连接不同的VHD。

我已经拥有通过WMI连接到远程VM主机的C#代码,并通过调用RequestStateChange来启动/停止VM,我想扩展它以便能够说“这里是VHD的路径,将其作为SCSI驱动器连接到此VM“。但是看list of WMI virtualization classes,我无法弄清楚如何做到这一点。

我找到的最接近的是MountMsvm_ImageManagementService方法,但这似乎是在当前操作系统中安装VHD,这不是我想要的。

2 个答案:

答案 0 :(得分:4)

必须使用Msvm_VirtualSystemManagementService.AddVirtualSystemResources添加合成磁盘(ResourceType。磁盘,ResourceSubType。 DiskSynthetic )。 Parent = SCSI控制器的WMI路径。

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);

然后使用Msvm_VirtualSystemManagementService.AddVirtualSystemResources附加虚拟硬盘(ResourceType。 StorageExtent ,ResourceSubType。 VHD )。 Parent =合成磁盘的WMI路径,连接 = * .vhd文件路径。

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);

使用Common Utilities for the Virtualization SamplesWMI Explorer

答案 1 :(得分:2)

另请参阅http://hypervlib.codeplex.com示例。

相关问题