Compartilhar via


CreateSwitchPort method of the Msvm_VirtualSwitchManagementService class

Creates a new port on a virtual switch.

Syntax

uint32 CreateSwitchPort(
  [in]  Msvm_VirtualSwitch REF VirtualSwitch,
  [in]  string                 Name,
  [in]  string                 FriendlyName,
  [in]  string                 ScopeOfResidence,
  [out] Msvm_SwitchPort    REF CreatedSwitchPort
);

Parameters

VirtualSwitch [in]

Type: Msvm_VirtualSwitch

The switch on which the port is to be created. See Msvm_VirtualSwitch.

Name [in]

Type: string

The name of the port. This name must be unique among all ports.

FriendlyName [in]

Type: string

A user-readable name for the port.

ScopeOfResidence [in]

Type: string

The authorization scope to be used for the access control policy of this virtual switch port.

CreatedSwitchPort [out]

Type: Msvm_SwitchPort

Upon successful completion of this method, this parameter contains the created switch port. See Msvm_SwitchPort.

Return value

Type: uint32

The method returns 0 if it succeeded synchronously. Any other return value indicates an error.

Completed with No Error (0)

Method Parameters Checked - Job Started (4096)

Failed (32768)

Access Denied (32769)

Not Supported (32770)

Status is unknown (32771)

Timeout (32772)

Invalid parameter (32773)

System is in used (32774)

Invalid state for this operation (32775)

Incorrect data type (32776)

System is not available (32777)

Out of memory (32778)

Remarks

Access to the Msvm_VirtualSwitchManagementService class might be restricted by UAC Filtering. For more information, see User Account Control and WMI.

Examples

The following C# sample creates a port on a virtual switch. The referenced utilities can be found in Common Utilities for the Virtualization Samples.

using System;
using System.Management;


namespace HyperVSamples
{
    class CreateSwitchPortClass
    {

        static ManagementObject GetVirtualSwitch(string switchName, ManagementScope scope)
        {
            string query = string.Format("select * from Msvm_VirtualSwitch where ElementName = '{0}'", switchName);
            
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, new ObjectQuery(query));

            ManagementObjectCollection virtualSwitchs = searcher.Get();

            ManagementObject virtualSwitch = null;

            foreach (ManagementObject instance in virtualSwitchs)
            {
                virtualSwitch = instance;
                break;
            }

            searcher.Dispose();
            return virtualSwitch;
        }

        static ManagementObject CreateSwitchPort(string switchName, string name, string friendlyName)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization", null);
            ManagementObject switchService = Utility.GetServiceObject(scope, "Msvm_VirtualSwitchManagementService");

            ManagementObject createdSwitchPort = null;

            ManagementBaseObject inParams = switchService.GetMethodParameters("CreateSwitchPort");

            ManagementObject virtualSwitch = GetVirtualSwitch(switchName, scope);

            inParams["FriendlyName"] = friendlyName;
            inParams["Name"] = name;
            inParams["VirtualSwitch"] = virtualSwitch.Path.Path;
            inParams["ScopeofResidence"] = null;
            ManagementBaseObject outParams = switchService.InvokeMethod("CreateSwitchPort", inParams, null);
            if ((UInt32)outParams["ReturnValue"] == ReturnCode.Completed)
            {
                createdSwitchPort = new ManagementObject(outParams["CreatedSwitchPort"].ToString());
                Console.WriteLine("{0} was created successfully", inParams["Name"]);
            }
            else
            {
                Console.WriteLine("Failed to create {0} switch port.", inParams["Name"]);
            }

            inParams.Dispose();
            outParams.Dispose();

            return createdSwitchPort;
        }


        static void Main(string[] args)
        {
            if (args != null && args.Length != 3)
            {
                Console.WriteLine("Usage: CreateSwitchPort SwitchName, Name, FriendlyName");
                Console.WriteLine("Example: CreateSwitchPort \"{0}\" {1} {2}",
                    "First_VirtalSwitch",
                    "FirstVirtualSwitchPort",
                    "First VirtualSwitch Port"
                    );
                return;
            }
            CreateSwitchPort(args[0], args[1], args[2]);
        }
    }
}

The following VBScript sample creates a port on a virtual switch.

option explicit 

dim objWMIService
dim switchService
dim fileSystem

const wmiSuccessful = 0

Main()

'-----------------------------------------------------------------
' Main
'-----------------------------------------------------------------
Sub Main()

    dim computer, objArgs
    dim switch, switchName,  name, friendlyName, createdSwitchPort
    
    set fileSystem = Wscript.CreateObject("Scripting.FileSystemObject")
    computer = "."

    set objWMIService = GetObject("winmgmts:\\" & computer & "\root\virtualization")
    set switchService = objWMIService.ExecQuery("select * from Msvm_VirtualSwitchManagementService").ItemIndex(0)
    
    set objArgs = WScript.Arguments
    if WScript.Arguments.Count = 3 then
       switchName = objArgs.Unnamed.Item(0)
       name = objArgs.Unnamed.Item(1)
       friendlyName = objArgs.Unnamed.Item(2)
    else
       WScript.Echo "usage: cscript CreateSwitchPort SwitchName Name FriendlyName"
       WScript.Echo "Example: CreateSwitchPort MyFirstSwitch FirstVirtualSwitchPort ""First VirtualSwitch Port""" 
       WScript.Quit(1)
    end if
        
    set switch = GetVirtualSwitch(switchName)
    if Not (switch Is Nothing) then
        set createdSwitchPort = CreateSwitchPort(switch, name, friendlyName)
        if Not(createdSwitchPort Is Nothing) then
            WriteLog "Done"
            WScript.Quit(0)
        End if
    else
        WriteLog "CreateSwitchPort failed"
        WScript.Quit(1)
    end if
End Sub

'-----------------------------------------------------------------
' Retrieve VirtualSwitch 
'-----------------------------------------------------------------
Function GetVirtualSwitch(friendlyName)
    dim query
    set GetVirtualSwitch = Nothing
    query = Format1("select * from Msvm_VirtualSwitch where ElementName = '{0}'", friendlyName)
    set GetVirtualSwitch= objWMIService.ExecQuery(query).ItemIndex(0)
End Function

'-----------------------------------------------------------------
' Create a virtual switch by calling CreateSwitch WMI method
'-----------------------------------------------------------------
Function CreateSwitchPort(virtualSwitch, name, friendlyName)
    dim objInParam, objOutParams
    
    set CreateSwitchPort = Nothing
    set objInParam = switchService.Methods_("CreateSwitchPort").InParameters.SpawnInstance_()
    objInParam.FriendlyName = friendlyName
    objInParam.Name = name
    objInParam.VirtualSwitch = virtualSwitch.Path_.Path
    objInParam.ScopeofResidence = null

    set objOutParams = switchService.ExecMethod_("CreateSwitchPort", objInParam)
    
    if objOutParams.ReturnValue = wmiSuccessful then
        set CreateSwitchPort = objWMIService.Get(objOutParams.CreatedSwitchPort)
    else
        WriteLog Format1("CreateSwitchPort failed with error code {0}", objOutParams.ReturnValue)
    end if    
End Function

'-----------------------------------------------------------------
' Create the console log files.
'-----------------------------------------------------------------
Sub WriteLog(line)
    dim fileStream
    set fileStream = fileSystem.OpenTextFile(".\CreateSwitchPort.log", 8, true)
    WScript.Echo line
    fileStream.WriteLine line
    fileStream.Close

End Sub

'------------------------------------------------------------------------------
' The string formatting functions to avoid string concatenation.
'------------------------------------------------------------------------------
Function Format1(myString, arg0)
    Format1 = Replace(myString, "{0}", arg0)
End Function

Requirements

Minimum supported client
None supported
Minimum supported server
Windows Server 2008
End of client support
None supported
End of server support
Windows Server 2012
Namespace
Root\Virtualization
MOF
WindowsVirtualization.mof

See also

Msvm_VirtualSwitchManagementService