Automate Your VPN Connection with PowerShell

Adam Bertram

Adam Bertram

Read more posts by this author.

I’m lazy. I don’t want to do anything twice, and if you read my blog I have a feeling you’re just as lazy as I am. I’ll automate anything! Here’s a prime example. Rather than waste 30 seconds of my time every day when I VPN into my client’s site and fire up remote desktop, I want to do it with a script.

All this script does is connect to a VPN gateway then connect to a device via remote desktop. It’ll save you 25 seconds of your time every day, but it’ll easily save you an hour’s worth of time over the year! I use this with the older Cisco IPSEC VPN client so I make no guarantees with other VPN clients. To prevent typing in your RDP password every time, save your RDP credentials to a file.

## One Time only. This is to securely store your VPN password to an encrypted text file
Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File encrypted_password.txt

## The VPN profile name configured in your client
$vpn_profile = 'Profile name'
$username = 'username'

## Decrypt the password
$enc_password = (gc .\encrypted_password.txt | ConvertTo-SecureString)

## Create the credentials
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist $username,$enc_password $password = $credentials.GetNetworkCredential().Password

## Pass the appropriate arguments to the VPN client EXE
Set-Location 'C:\Program Files (x86)\Cisco Systems\VPN Client'
.\vpnclient.exe connect $vpn_profile user $username pwd $password

## Use this if you have a need to disconnect via script
#Set-Location 'C:\Program Files (x86)\Cisco Systems\VPN Client'
#.\vpnclient.exe disconnect

## RDP to a device. mstsc /v:HOSTNAME /multimon

Download a copy of this script via my GitHub repo.

Subscribe to Adam the Automator

Get the latest posts delivered right to your inbox

Looks like you're offline!