If you do not get a dedicated IP address when connecting to the VPN server, you must manually modify the static routes after each connection. The following description will help you automatically set up static routes after connecting.
- Start the Windows PowerShell (Admin) console
- After authentication, verify that we have the right to boot RemoteSigned scripts.
PS C:\WINDOWS\system32> Get-ExecutionPolicy
- If not, issue the following command:
PS C:\WINDOWS\system32> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
Then press theA
key to appear. - Then create a folder where the two scripts will reside:
PS C:\WINDOWS\system32> New-Item -ItemType directory -Path C:\Scripts\
- Enter the directory that you created, and then create the following file: VPN-conn.ps1 and insert the following code:
## # Add IP routes across a VPN via a DHCP assigned IP address # author Richard Buz 29.01.2019 ## # Route IP address $ips = @("192.168.0.0", "10.20.30.0", "172.19.0.0") # VPN connection IP $vpnIP = "192.168.50." # Get the IP address of the VPN connection $vpnip = ipconfig | findstr $vpnIP # If we don't have an IP address on the VPN, error and quit if (!$vpnip) { "You do not have an IP address on the VPN" exit } # Parsing VPN IP $vpnip = $vpnip.trim().split(" ")[-1] # Delete routes if existing foreach($ip in $ips) { $hasRoute = route print | findstr $ip if($hasRoute) { "Deleting route " + $ip route delete $ip } } # Add whatever routes we need foreach($ip in $ips) { "Adding route " + $ip route add $ip MASK 255.255.255.0 $vpnip }
- Save the file, and then create another file called VPN-disconn.ps1
Paste the following code:
## # Remove existing VPN routes # author Richard Buz 29.01.2019 ## # Route IP address $ips = @("192.168.0.0", "10.20.30.0", "172.19.0.0") # Delete existing VPN routes foreach($ip in $ips) { $hasRoute = route print | findstr $ip if($hasRoute) { "Deleting route " + $ip route delete $ip } }
- Then, in PowerShell, ask the name of the VPN connection:
PS C:\WINDOWS\system32> Get-VpnConnection
- The following two commands will set the scheduled tasks after connection and disconnection. For commands, the vpn-connection-name variable at the end of the line must be changed to the name of the connection in the Get-VpnConnection command output.
- Scheduled to run after joining:
schtasks /create /RU "SYSTEM" /NP /F /TN "VPN Connect Update" /TR "Powershell.exe -NonInteractive -command c:\Scripts\VPN-conn.ps1" /SC ONEVENT /EC Application /MO " *[System[(Level=4 or Level=0) and (EventID=20225)]] and *[EventData[Data='vpn-connection-name']]"
- Timed to run after disconnection:
schtasks /create /RU "SYSTEM" /NP /F /TN "VPN Disconnect Update" /TR "Powershell.exe -NonInteractive -command c:\Scripts\VPN-disconn.ps1" /SC ONEVENT /EC Application /MO " *[System[(Level=4 or Level=0) and (EventID=20226)]] and *[EventData[Data='vpn-connection-name']]"
- Scheduled to run after joining:
Source: