【问题标题】:Cannot connect Hyper-V VM Network Adapter to a Hyper-V Switch via WMI in C#无法通过 C# 中的 WMI 将 Hyper-V VM 网络适配器连接到 Hyper-V 交换机
【发布时间】:2023-03-03 19:42:02
【问题描述】:

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

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

【问题讨论】:

    标签: c# wmi hyper-v


    【解决方案1】:

    已解决:

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

    【讨论】:

      猜你喜欢
      • 2011-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-05
      • 1970-01-01
      • 1970-01-01
      • 2016-10-24
      • 1970-01-01
      相关资源
      最近更新 更多