Scripts
General

How to update WSL DNS settings when using a VPN
Problem: When connecting with a VPN, WSL's gateway setting does NOT get updated. "apt update" will stop working, for example. These instructions depend on your VPN utility executing a script as soon as the link is up.
- In WSL edit /etc/wsl.conf with the following, then restart it
[network]
generateResolvConf = false
- Install BurntToast from Powershell:
Install-Module BurntToast
- In WSL create setdns
echo "nameserver $1" >/etc/resolv.conf
Then make it executable
chmod u+x setdns
- In windows create setdns.ps1
# Get VPN Gateway
$gw = Get-WmiObject -Class Win32_IP4RouteTable |
where { $.destination -eq '0.0.0.0' -and $.mask -eq '128.0.0.0'} |
Sort-Object metric1 | select nexthop -ExpandProperty nexthop
# Run script that sets resolv.conf
wsl ~/setdns $gw
New-BurntToastNotification -Text "Set WSL Gateway to $gw"
exit
- In the VPN application, find the "VPN Up" event handler and set it to
powershell.exe -noexit "& ""C:\PATH\setdns.ps1"""
Where PATH is the directory containing setdns.ps1
Note: Typically the VPN app will display the current gateway being used. In step 4, if no gateway was found (or it found your local gateway instead of the VPN's gateway), the mask may need to be '0.0.0.0' instead of '128.0.0.0', depending on your VPN service. You can double check by looking at the output of the following command (in Windows), and match to your current gateway, e.g. 1.2.3.4
netstat -rn | find "1.2.3.4"
Look at the line where the gateway is the third column - the mask is in the second column.
Now every time you connect, the gateway will be updated in WSL and a toast will display with the new value.
References

Powershell
