C# 无法通过C中的WMI将Hyper-V VM网络适配器连接到Hyper-V交换机#
我很难将一个特定的、现有的网络适配器连接到一个现有的交换机。我可以创建一个新的网络适配器,并通过在线发布的几个示例将其连接到我的虚拟机,但无法执行额外的步骤。下面的函数找到我的网络适配器并执行,不会出错,但不会建立连接。非常感谢您的帮助C# 无法通过C中的WMI将Hyper-V VM网络适配器连接到Hyper-V交换机#,c#,wmi,hyper-v,C#,Wmi,Hyper V,我很难将一个特定的、现有的网络适配器连接到一个现有的交换机。我可以创建一个新的网络适配器,并通过在线发布的几个示例将其连接到我的虚拟机,但无法执行额外的步骤。下面的函数找到我的网络适配器并执行,不会出错,但不会建立连接。非常感谢您的帮助 **EDIT: Solved, see code below.** 已解决: public static void ConnectInterfaceToSwitch(string VmName, string networkInterfaceName,
**EDIT: Solved, see code below.**
已解决:
public static void ConnectInterfaceToSwitch(string VmName, string networkInterfaceName, string switchName)
{
ManagementScope scope = new ManagementScope(@"root\virtualization\v2");
ManagementObject mgtSvc = WmiUtilities.GetVirtualMachineManagementService(scope);
ManagementObject ethernetSwitch = NetworkingUtilities.FindEthernetSwitch(switchName, scope);
ManagementObject virtualMachine = WmiUtilities.GetVirtualMachine(VmName, scope);
ManagementObject virtualMachineSettings = WmiUtilities.GetVirtualMachineSettings(virtualMachine);
ManagementObjectCollection portsSettings = virtualMachineSettings.GetRelated("Msvm_SyntheticEthernetPortSettingData", "Msvm_VirtualSystemSettingDataComponent", null, null, null, null, false, null);
{
foreach (ManagementObject portSettings in portsSettings)
{
if (portSettings["ElementName"].Equals(networkInterfaceName))
{
Console.WriteLine("Adapter found: " + networkInterfaceName);
ManagementObjectCollection connections = portSettings.GetRelated("Msvm_EthernetPortAllocationSettingData");
foreach (ManagementObject connection in connections)
{
connection["HostResource"] = new string[] { ethernetSwitch.Path.Path };
connection["EnabledState"] = 2; // 2 means "Enabled"
ManagementBaseObject inParams = mgtSvc.GetMethodParameters("ModifyResourceSettings");
inParams["ResourceSettings"] = new string[] { connection.GetText(TextFormat.WmiDtd20) };
ManagementBaseObject outParams = mgtSvc.InvokeMethod("ModifyResourceSettings", inParams, null);
WmiUtilities.ValidateOutput(outParams, scope);
Console.WriteLine(string.Format(CultureInfo.CurrentCulture, "Connected VM '{0}' to switch '{1}'.", VmName, switchName));
}
}
}
}
}