Reconfigure Hyper-V External switch to the correct Network Adapter

If you use Hyper-V on your laptop, then you will probably recognize this… You worked at home, go to the Office and use the Wi-Fi there instead of the wired connection at home. You boot your VM and… No network?! *sigh* And you have to change the External Switch again in your Hyper-V configuration. In this blog post, I will show you a way to change it automatically using PowerShell.

How the script works

It’s a PowerShell function in which you specify the External Switch that needs a change in the network adapter that it’s using. The script looks for the adapter with the lowest Interface Index as being the best adapter to choose and reconfigures your External Switch to use that one. If you schedule this script to run one minute after user logon, you should always have a working External Hyper-V Switch šŸ˜‰

Running the script

You can run the Set-CorrectHyperVExternalSwitchAdapter function with the -SwitchName parameter followed by the External Switch name, in my case that would be Set-CorrectHyperVExternalSwitchAdapter -SwitchName External. When done, and without errors, it should state something like this:

Reconfiguring External Hyper-V Switch External to use Network Adapter Ethernet 6

The script

Below is the script that I use, safe it to c:\scripts for example, and create a Scheduled Task (Running as System or a User Account with enough permissions) and you should be good to go!

function Set-CorrectHyperVExternalSwitchAdapter {
    param (
        [parameter(Mandatory = $true)][string]$SwitchName
    #retrieve external switch(es) and get Network adapter with Up state
    $externalswitch = Get-VMSwitch | Where-Object Name -eq $SwitchName
    $connectedadapter = Get-NetAdapter | Where-Object Status -eq Up | Sort-Object ifIndex | Where-Object {$_.Name -NotMatch 'vEthernet' -and $_.Name -notmatch 'Network Bridge'} | Select-Object -First 1

    #Set VMSwitch(es) properties so that the connected adapter is configured
    try {
        Set-VMSwitch $externalswitch.Name -NetAdapterName $connectedadapter.Name -ErrorAction Stop
        Write-Host ("Reconfiguring External Hyper-V Switch {0} to use Network Adapter {1}" -f $SwitchName, $connectedadapter.Name) -ForegroundColor Green
    catch {
        Write-Warning ("Failed reconfiguring External Hyper-V Switch {0} to use Network Adapter {1}" -f $SwitchName, $connectedadapter.Name)

Download the script(s) from GitHub here

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.