Adding route automatically after a successful VPN connection in Windows 10

On Win 10, Powershell has a cmdlet available that adds routes on VPN connection and removes them again when the VPN is disconnected: Add-VpnConnectionRoute. It works without having to specify the interface ID.

The basic syntax is like this:

Add-VpnConnectionRoute -ConnectionName "VPN Connection Name" -DestinationPrefix 10.0.0.0/16

After entering this command, the routes will be created/removed automatically on connection/disconnection of the VPN.


Finally I couldn't make it work... so, sadly decided to look for an alternative. I made a batch file using rasdial which works like a charm. The only "problem" is the route command needs to be launched with elevated privileges. That's because I put a runas with the /savedcred argument which will ask only once for the password and then it will work automatically. Then, for the vpn you can put your password (in clear!) or leave set mypass="*" to ask for the password everytime.

Here is my code:

@echo off

cls
echo.

REM put your VPN connection name here
set myvpn="Your VPN name"
REM put your user here
set myuser="foo"
REM put your pass here. Leave * for asking
set mypass="testpass"
REM put your win admin user here
set winadmin="administrator"
REM put your network route here
set network="192.168.8.0"
REM put your network mask here
set mask="255.255.255.0"
REM put your gateway mask here
set gateway="192.168.1.1"

ipconfig | find /i %myvpn% > nul 2>&1

if %ERRORLEVEL% == 0 (

    echo "VPN already connected. Disconnecting..."
    echo.
    rasdial %myvpn% /disconnect
    runas.exe /user:%winadmin% /savedcred "route delete %network% mask %mask% %gateway%"

) else if %ERRORLEVEL% == 1 (

    echo "VPN not connected. Connecting..."
    echo.
    rasdial %myvpn% %myuser% %mypass%
    runas.exe /user:%winadmin% /savedcred "route add %network% mask %mask% %gateway%"
)

I hope this helps to somebody.