CreateSwitchPort Method of the Msvm_VirtualSwitchManagementService Class

Creates a new port on a virtual switch.

Syntax

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

Parameters

VirtualSwitch [in]

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

Name [in]

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

FriendlyName [in]

A user-readable name for the port.

ScopeOfResidence [in]

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

CreatedSwitchPort [out]

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

Return Value

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

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_VirualSwitch",
                    "FirstVirualSwitchPort",
                    "First VirualSwitch 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 FirstVirualSwitchPort ""First VirualSwitch 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(firendlyName)
    dim query
    set GetVirtualSwitch = Nothing
    query = Format1("select * from Msvm_VirtualSwitch where ElementName = '{0}'", firendlyName)
    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 formating functions to avoid string concatenation.
'------------------------------------------------------------------------------
Function Format1(myString, arg0)
    Format1 = Replace(myString, "{0}", arg0)
End Function

Requirements

Minimum supported clientNone supported
Minimum supported serverWindows Server 2008
MOFWindowsVirtualization.mof
Namespace\\.\Root\Virtualization

See Also

Msvm_VirtualSwitchManagementService

Send comments about this topic to Microsoft

Build date: 10/8/2009

Tags :


Page view tracker