Hyper-V How To: Connect a Virtual Switch to a VM using Script

Some friends here on the Hyper-V team shared a PowerShell 2.0 script for connecting a virtual switch to a VM:

# Connect Virtual Switch to VM

param(
    [string]$vsName = $(throw "Must specify virtual switch name"),
    [string]$vmName = $(throw "Must specify virtual machine name"),
    [string]$switchPortName = [guid]::NewGuid().guid
)

$vm = gwmi -namespace root\virtualization Msvm_ComputerSystem -filter "ElementName = '$vmName'"

# Find the NIC from the virtual system setting data (assuming there is only one)
$vssd = gwmi -namespace root\virtualization `
    -query "Associators of {$vm} where ResultClass = Msvm_VirtualSystemSettingData" |`
    where{$_.SettingType -eq 3}
$synthEth = gwmi -namespace root\virtualization `
    -query "Associators of {$vssd} where ResultClass = Msvm_SyntheticEthernetPortSettingData"

# Get the virtual switch (assuming only one in the system)
$vSwitch = gwmi -namespace root\virtualization Msvm_VirtualSwitch -filter "ElementName = '$vsName'"

# Get the virtual switch and virtual system services
$vsms = gwmi -namespace root\virtualization Msvm_VirtualSwitchManagementService
$vmms = gwmi -namespace root\virtualization Msvm_VirtualSystemManagementService

# Use the switch service to create a new switch port
$result = $vsms.CreateSwitchPort($vSwitch, $switchPortName, "VM Switch Port", "")
if($result.ReturnValue -ne 0){
    return $result.ReturnValue
}
$switchPort = [wmi]$result.CreatedSwitchPort

# Set the NIC (synthetic ethernet port) connection to the switch port, and
# then modify the virtual system
$synthEth.Connection = @($switchPort.__PATH)
$result = $vmms.ModifyVirtualSystemResources($vm,@($synthEth.GetText(1)))
if($result.ReturnValue -eq 4096){
    # A Job was started, and can be tracked using its Msvm_Job instance
    $job = [wmi]$result.Job
    # Wait for job to finish
    while($job.jobstate -lt 7){$job.get()}
    # Return the Job's error code
    return $job.ErrorCode
}
# Otherwise, the method completed
return $result.ReturnValue

For more info on how to use PS cmdlets see: https://www.microsoft.com/technet/scriptcenter/topics/msh/cmdlets/index.mspx

See also James O’Neil’s New and improved PowerShell Library for Hyper-V. Now with more functions and... documentation!

For all 35 sample Hyper-V PS1 scripts in a zipfile, go to: Hyper-V PowerShell Example Scripts.zip-download