Windows PowerShell script for adding IP routes across a VPN
At my office we use a Microsoft ISA server for our firewall/VPN server. We have three discreet IP subnets within our private network. 192.168.5.0/24, 192.168.6.0/24, and 192.168.7/24. When I establish a VPN connection from the external network I get an IP address on the 192.168.6.0/24 network.
I have my VPN connection set up to not use the default gateway on the remote network. This prevents all of my internet traffic from being routed over the VPN while I am connected to it… the problem is that if I need to access a resource on the 192.168.5.0/24 or 192.168.7.0/24 networks, I have to manually add routes to them across the VPN.
The process was:
- Find out what IP I was assigned on the VPN
- Add an IP route to 192.168.5.0/24
- Add an IP route to 192.168.7.0/24
If I was always assigned the same IP address on the VPN, I could have just put the commands in a batch file, but the IP address is dynamically assigned from a DHCP server and is always different than it was the last time. So this is what I used to do:

That is a lot of typing! I’d been meaning to play around with Windows PowerShell anyhow, and decided to write a script to automate this task in PowerShell. This is what I came up with:
# vpn.ps1
#
# Add IP routes across a VPN via a DHCP assigned IP address
#
# Get the IP address of the VPN connection
$vpnip = ipconfig | findstr "192.168.6."
# 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
}
# Trim any leading/trailing whitespace
$vpnip = $vpnip.Trim()
# Split the contents of $vpnip in to an array
$vpnip = $vpnip.Split(" ")
# Find out the depth of our IP address in the array
$bit = $vpnip.Length - 1
# Get out just our IP address on the VPN
$vpnip = $vpnip[$bit]
# Add whatever routes we need
route add 192.168.5.0 MASK 255.255.255.0 $vpnip
route add 192.168.7.0 MASK 255.255.255.0 $vpnip
I save the script as vpn.ps1 and put it in my “scripts” directory in my profile directory. Then I just put a shortcut on my desktop to powershell.exe C:\Users\chillman\scripts\vpn.ps1. Now I just connect to the vpn, launch my shortcut and I’m ready to go. Hopefully this will be useful to someone.

