DEV Community

Stanislav Berkov
Stanislav Berkov

Posted on • Updated on

PS script to fix WSL2 and VM network connectivity while using Cisco VPN

Starting working remotely I realized that WSL2 loses network access once I connect to corporate network via VPN. This can be fixed by adjusting network connection metrics. To make it work ensure you start WSL2 before connecting to VPN. If you start WSL2 after you connected to VPN metric adjustment will not work. You will have to disconnect VPN and reconnect again and readjust metrics.

Script for metric re-adjustment

# Get the ID and security principal of the current user account
$myWindowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal = new-object System.Security.Principal.WindowsPrincipal($myWindowsID)

# Get the security principal for the Administrator role
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator

# Check to see if we are currently running "as Administrator"
if ($myWindowsPrincipal.IsInRole($adminRole)) {
    # We are running "as Administrator" - so change the title and background color to indicate this
    $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
    $Host.UI.RawUI.BackgroundColor = "DarkBlue"
    clear-host
}
else {
    # We are not running "as Administrator" - so relaunch as administrator

    # Create a new process object that starts PowerShell
    $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";

    # Specify the current script path and name as a parameter
    $newProcess.Arguments = $myInvocation.MyCommand.Definition;

    # Indicate that the process should be elevated
    $newProcess.Verb = "runas";

    # Start the new process
    [System.Diagnostics.Process]::Start($newProcess);

    # Exit from the current, unelevated, process
    exit
}

Write-Output "Setting Cisco AnyConnect metric to 4000"
Get-NetAdapter | Where-Object { $_.InterfaceDescription -Match "Cisco AnyConnect" } | Set-NetIPInterface -InterfaceMetric 4000

Write-Output "Setting vEthernet (WSL* metric to 1"
Get-NetIPInterface -InterfaceAlias "vEthernet (WSL*" | Set-NetIPInterface -InterfaceMetric 1

Write-Output "Setting vEthernet (Default Switch) metric to 1"
Get-NetIPInterface -InterfaceAlias "vEthernet (Default Switch)" | Set-NetIPInterface -InterfaceMetric 1

Write-Output "Done!"
# echo "$PSScriptRoot"
# pause

start-sleep -seconds 2
Enter fullscreen mode Exit fullscreen mode

Idea of self-elevated script taken from https://learn.microsoft.com/en-us/archive/blogs/virtual_pc_guy/a-self-elevating-powershell-script

Top comments (0)