In the latest Windows 10 builds, you can automatically add static routes when establishing a VPN connection. When the VPN connection is terminated, the route is automatically removed from the Windows routing table. To add an IPv4 or IPv6 route for a VPN connection, the Add-VpnConnectionRoute PowerShell cmdlet is used.
Suppose, you want only traffic of two subnets (
10.1.0.0/16) to be routed through your VPN connection, and other traffic to go through your provider (ISP).
Open the PowerShell console and display the list of configured VPN connections in Windows:
First of all, uncheck the Use default gateway in the remote network option. You can do it in the VPN connection properties in the Control Panel or using the PowerShell command Set-VpnConnection:
Set-VpnConnection –Name workVPN -SplitTunneling $True
Let’s add two static routes for our VPN connection:
Add-VpnConnectionRoute -ConnectionName workVPN -DestinationPrefix 192.168.11.0/24 –PassThru
Add-VpnConnectionRoute -ConnectionName workVPN -DestinationPrefix 10.1.0.0/16 –PassThru
DestinationPrefix : 192.168.11.0/24 InterfaceIndex : InterfaceAlias : workVPN AddressFamily : IPv4 NextHop : 0.0.0.0 Publish : 0 RouteMetric : 1
If your VPN connection is active, you will need to reconnect so that new routes are added to the routing table.
New routes are bound to the VPN connection and are added only when the connection is established. When you disconnect from the VPN server, the routes are automatically removed.
Disconnect from the VPN and check the routing table. The route to your remote network has been removed automatically, and
Get-NetRoute returns that the route was not found:
Get-NetRoute : No MSFT_NetRoute objects found with property 'DestinationPrefix' equal to '192.168.11.0/24'. Verify the value of the property and retry. CmdletizationQuery_NotFound_DestinationPrefix,Get-NetRoute
To completely remove a static route for a VPN connection, use the command:
Remove-VpnConnectionRoute -ConnectionName workVPN -DestinationPrefix 192.168.111.0/24 -PassThru
In previous Windows versions (Windows 7/ Windows Server 2008R2), to dynamically add routes after establishing a VPN connection, you had to use the CMAK and various scripts with add route commands.
For example, you can create a batch file vpn_route.netsh to add some static routes.
interface ipv4 add route prefix=192.168.11.24 interface="workVPN" store=active add route prefix=10.1.0.0/16 interface="workVPN" store=active exit
You can run this file using the Task Scheduler that triggers after the VPN connection is established (the RasMan 20225 event in the Event Viewer).
schtasks /create /F /TN "Add VPN routes" /TR "netsh -f C:\PS\vpn_route.netsh" /SC ONEVENT /EC Application /RL HIGHEST /MO "*[System[(Level=4 or Level=0) and (EventID=20225)]] and *[EventData[Data='My VPN']]"