无法通过C#中的WMI将Hyper-V VM网络适配器连接到Hyper-V交换机

时间:2016-02-04 22:10:58

标签: c# wmi hyper-v

我在将特定的现有网络适配器连接到现有交换机时遇到了一些困难。我可以通过在线发布的几个示例创建一个新的网络适配器并将其连接到我的VM,但无法完成额外的步骤。以下函数找到我的网络适配器并执行而没有错误,但不会进行连接。非常感谢任何帮助!

**EDIT: Solved, see code below.**

1 个答案:

答案 0 :(得分:0)

解决:

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