ConnectVmToSwitch(
            string virtualMachineName,
            string switchName)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            using (ManagementObject managementService = WmiUtilities.GetVirtualMachineManagementService(scope))

                //
                // Find the Ethernet switch we want to connect to.
                //
                using (ManagementObject ethernetSwitch = NetworkingUtilities.FindEthernetSwitch(switchName, scope))

                    //
                    // Find the virtual machine we want to connect.
                    //
                    using (ManagementObject virtualMachine = WmiUtilities.GetVirtualMachine(virtualMachineName, scope))

                        //
                        // Get the virtual machine's settings object which is used to make configuration changes.
                        //
                        using (ManagementObject virtualMachineSettings = WmiUtilities.GetVirtualMachineSettings(virtualMachine))

                            //
                            // Add a new synthetic Network Adapter device to the virtual machine.
                            //
                            using (ManagementObject syntheticAdapter = NetworkingUtilities.AddSyntheticAdapter(virtualMachine, scope))

                                //
                                // Now that we have added a network adapter to the virtual machine we can configure its
                                // connection settings.
                                //
                                using (ManagementObject connectionSettingsToAdd =
                                           NetworkingUtilities.GetDefaultEthernetPortAllocationSettingData(scope))
                                {
                                    connectionSettingsToAdd["Parent"]       = syntheticAdapter.Path.Path;
                                    connectionSettingsToAdd["HostResource"] = new string[] { ethernetSwitch.Path.Path };

                                    //
                                    // Now add the connection settings.
                                    //
                                    using (ManagementBaseObject addConnectionInParams =
                                               managementService.GetMethodParameters("AddResourceSettings"))
                                    {
                                        addConnectionInParams["AffectedConfiguration"] = virtualMachineSettings.Path.Path;
                                        addConnectionInParams["ResourceSettings"]      =
                                            new string[] { connectionSettingsToAdd.GetText(TextFormat.WmiDtd20) };

                                        using (ManagementBaseObject addConnectionOutParams =
                                                   managementService.InvokeMethod("AddResourceSettings", addConnectionInParams, null))
                                        {
                                            WmiUtilities.ValidateOutput(addConnectionOutParams, scope);
                                        }
                                    }
                                }

            Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                            "Successfully connected virtual machine '{0}' to switch '{1}'.",
                                            virtualMachineName, switchName));
        }
        CreateExternalSwitch(
            string externalAdapterName,
            string switchName,
            string switchNotes)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            string[] ports;

            //
            // Get the external adapter we are connecting to.
            //
            using (ManagementObject externalAdapter =
                       NetworkingUtilities.FindExternalAdapter(externalAdapterName, scope))

                //
                // Get the hosting computer system. The internal port we create needs to be configured
                // to connect to the hosting computer system.
                //
                using (ManagementObject hostComputerSystem = WmiUtilities.GetHostComputerSystem(scope))

                    //
                    // Get the default Msvm_EthernetPortAllocationSettingData instance that we can use to
                    // configure our external port connection for the switch.
                    // Use the same switch name, appended with "_External", for the port name.
                    // You can use any port name that you like.
                    //
                    using (ManagementObject externalPortToCreate =
                               NetworkingUtilities.GetDefaultEthernetPortAllocationSettingData(scope))
                    {
                        externalPortToCreate["ElementName"]  = switchName + "_External";
                        externalPortToCreate["HostResource"] = new string[] { externalAdapter.Path.Path };

                        //
                        // Clone the externalPort connection and configure it for the internal port.
                        // Use the same switch name, appended with "_Internal", for the port name.
                        // You can use any port name that you like.
                        //
                        using (ManagementObject internalPortToCreate =
                                   (ManagementObject)externalPortToCreate.Clone())
                        {
                            internalPortToCreate["ElementName"]  = switchName + "_Internal";
                            internalPortToCreate["HostResource"] = new string[] { hostComputerSystem.Path.Path };

                            //
                            // Now create the switch with the two ports.
                            //
                            ports = new string[] {
                                externalPortToCreate.GetText(TextFormat.WmiDtd20),
                                internalPortToCreate.GetText(TextFormat.WmiDtd20)
                            };
                        }
                    }

            CreateSwitch(switchName, switchNotes, ports, scope);

            Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                            "The external switch '{0}' was created successfully.", switchName));
        }
        CreateExternalOnlySwitch(
            string externalAdapterName,
            string switchName,
            string switchNotes)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            string[] ports;

            //
            // Get the external adapter we are connecting to.
            //
            using (ManagementObject externalAdapter =
                       NetworkingUtilities.FindExternalAdapter(externalAdapterName, scope))

                //
                // Get the default Msvm_EthernetPortAllocationSettingData instance that we can use to
                // configure our external port connection for the switch.
                // Use the same switch name, appended with "_External", for the port name.
                // You can use any port name that you like.
                //
                using (ManagementObject portToCreate =
                           NetworkingUtilities.GetDefaultEthernetPortAllocationSettingData(scope))
                {
                    portToCreate["ElementName"]  = switchName + "_External";
                    portToCreate["HostResource"] = new string[] { externalAdapter.Path.Path };

                    //
                    // Now create the switch with the external port.
                    //
                    ports = new string[] { portToCreate.GetText(TextFormat.WmiDtd20) };
                }

            CreateSwitch(switchName, switchNotes, ports, scope);

            Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                            "The external-only switch '{0}' was created successfully.", switchName));
        }
        CreateInternalSwitch(
            string switchName,
            string switchNotes)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            string[] ports;

            //
            // Get the hosting computer system. When connecting an internal port, we specify the
            // path to the hosting computer system as what the port should connect to.
            //
            using (ManagementObject hostComputerSystem = WmiUtilities.GetHostComputerSystem(scope))

                //
                // Get the default Msvm_EthernetPortAllocationSettingData instance that we can use to
                // configure our internal port connection for the switch.
                // Use the same switch name, appended with "_Internal", for the port name.
                // You can use any port name that you like.
                //
                using (ManagementObject portToCreate =
                           NetworkingUtilities.GetDefaultEthernetPortAllocationSettingData(scope))
                {
                    portToCreate["ElementName"]  = switchName + "_Internal";
                    portToCreate["HostResource"] = new string[] { hostComputerSystem.Path.Path };

                    //
                    // Now create the switch with the internal port.
                    //
                    ports = new string[] { portToCreate.GetText(TextFormat.WmiDtd20) };
                }

            CreateSwitch(switchName, switchNotes, ports, scope);

            Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                            "The internal switch '{0}' was created successfully.", switchName));
        }
        AddPorts(
            string switchName,
            string externalAdapterName)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            string ethernetSwitchSettingPath;
            string portToCreateText;

            ObjectQuery externalAdapterQuery = new ObjectQuery(string.Format(CultureInfo.InvariantCulture,
                                                                             "select * from Msvm_ExternalEthernetPort where Name=\"{0}\"", externalAdapterName));

            //
            // When modifying the switch, we need to pass in its configuration object.
            //
            using (ManagementObject ethernetSwitch = NetworkingUtilities.FindEthernetSwitch(switchName, scope))
                using (ManagementObject ethernetSwitchSetting = WmiUtilities.GetFirstObjectFromCollection(
                           ethernetSwitch.GetRelated("Msvm_VirtualEthernetSwitchSettingData",
                                                     "Msvm_SettingsDefineState",
                                                     null, null, null, null, false, null)))
                {
                    ethernetSwitchSettingPath = ethernetSwitchSetting.Path.Path;
                }

            //
            // Get the external adapter that we want to add a connection to.
            //
            using (ManagementObjectSearcher externalAdapterExecute =
                       new ManagementObjectSearcher(scope, externalAdapterQuery))
                using (ManagementObjectCollection externalAdapterCollection = externalAdapterExecute.Get())
                {
                    if (externalAdapterCollection.Count == 0)
                    {
                        throw new ManagementException(string.Format(CultureInfo.InvariantCulture,
                                                                    "There is no external adapter with the name {0}.",
                                                                    externalAdapterName));
                    }

                    using (ManagementObject externalAdapter =
                               WmiUtilities.GetFirstObjectFromCollection(externalAdapterCollection))

                        //
                        // Get the default Msvm_EthernetPortAllocationSettingData instance, which we can use to
                        // configure our external port connection for the switch.
                        // Use the same switch name, appended with "_External", for the port name.
                        // You can use any port name that you like.
                        //
                        using (ManagementObject portToCreate =
                                   NetworkingUtilities.GetDefaultEthernetPortAllocationSettingData(scope))
                        {
                            portToCreate["ElementName"]  = switchName + "_External";
                            portToCreate["HostResource"] = new string[] { externalAdapter.Path.Path };

                            portToCreateText = portToCreate.GetText(TextFormat.WmiDtd20);
                        }
                }

            //
            // Now add the port connection to the switch.
            //
            using (ManagementObject switchService = NetworkingUtilities.GetEthernetSwitchManagementService(scope))
                using (ManagementBaseObject inParams =
                           switchService.GetMethodParameters("AddResourceSettings"))
                {
                    inParams["AffectedConfiguration"] = ethernetSwitchSettingPath;
                    inParams["ResourceSettings"]      = new string[] { portToCreateText };

                    using (ManagementBaseObject outParams =
                               switchService.InvokeMethod("AddResourceSettings", inParams, null))
                    {
                        WmiUtilities.ValidateOutput(outParams, scope);
                    }
                }

            Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                            "We added an external port connection to '{0}' on the switch '{1}'.",
                                            externalAdapterName, switchName));
        }
        ConnectVmUsingResourcePool(
            string virtualMachineName,
            string resourcePoolName)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            using (ManagementObject managementService = WmiUtilities.GetVirtualMachineManagementService(scope))

                //
                // Find the virtual machine we want to connect.
                //
                using (ManagementObject virtualMachine = WmiUtilities.GetVirtualMachine(virtualMachineName, scope))

                    //
                    // As a sanity check, verify that the specified resource pool exists by querying for it.
                    //
                    using (ManagementObject resourcePool = WmiUtilities.GetResourcePool(
                               "33",
                               "Microsoft:Hyper-V:Ethernet Connection",
                               resourcePoolName,
                               scope))

                        //
                        // Get the virtual machine's settings object which is used to make configuration changes.
                        //
                        using (ManagementObject virtualMachineSettings = WmiUtilities.GetVirtualMachineSettings(virtualMachine))

                            //
                            // Add a new synthetic Network Adapter device to the virtual machine.
                            //
                            using (ManagementObject syntheticAdapter = NetworkingUtilities.AddSyntheticAdapter(virtualMachine, scope))

                                //
                                // Now that we have added a network adapter to the virtual machine, we can configure its
                                // connection settings.
                                //
                                using (ManagementObject connectionSettingsToAdd =
                                           NetworkingUtilities.GetDefaultEthernetPortAllocationSettingData(scope))
                                {
                                    connectionSettingsToAdd["Parent"] = syntheticAdapter.Path.Path;

                                    //
                                    // Rather than specifying which switch to connect to, we specify which pool to look in.
                                    //
                                    connectionSettingsToAdd["PoolId"] = resourcePoolName;

                                    //
                                    // Now add the connection settings.
                                    //
                                    using (ManagementBaseObject addConnectionInParams =
                                               managementService.GetMethodParameters("AddResourceSettings"))
                                    {
                                        addConnectionInParams["AffectedConfiguration"] = virtualMachineSettings.Path.Path;
                                        addConnectionInParams["ResourceSettings"]      =
                                            new string[] { connectionSettingsToAdd.GetText(TextFormat.WmiDtd20) };

                                        using (ManagementBaseObject addConnectionOutParams =
                                                   managementService.InvokeMethod("AddResourceSettings", addConnectionInParams, null))
                                        {
                                            WmiUtilities.ValidateOutput(addConnectionOutParams, scope);
                                        }
                                    }
                                }

            Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                            "Successfully created dynamic connection from virtual machine '{0}' to resource pool '{1}'.",
                                            virtualMachineName, resourcePoolName));
        }