Powershell script to auto connect to your VPN on startup

This guide will show you how to connect to a VPN on startup and how to run a script that will automatically reconnect to that VPN even if there is a service disconnection. If you already have a VPN setup in Windows great! Otherwise checkout this guide on how to setup a L2TP/IPSEC VPN on Windows.

Powershell and Rasdial.exe make it easy to automate your Windows 10 VPN connection.

Steps for adding a Powershell script to auto connect to your VPN on startup

  1. Setup your VPN in Windows
    Hopefully you have already setup your VPN connection, if not you can follow this guide on how to setup a L2TP/IPSEC VPN on Windows. You will need the 'Name' of this VPN connection as well as the credentials in the next steps.
    VPN Name

  2. Save this powershell script as 'autovpn.ps1' and replace the values for $vpnname, $vpnusername, and $vpnpassword
    while ($true) { $vpnname = "YOURVPNCONNECTIONNAME" $vpnusername = "YOURUSERNAME" $vpnpassword = "YOURPASSWORD" $vpn = Get-VpnConnection | where {$_.Name -eq $vpnname} if ($vpn.ConnectionStatus -eq "Disconnected") { $cmd = $env:WINDIR + "\System32\rasdial.exe" $expression = "$cmd ""$vpnname"" $vpnusername $vpnpassword" Invoke-Expression -Command $expression } start-sleep -seconds 30 }
    This script will check your VPN status every 30 seconds, and if the status is disconnected, it will use the windows remote access dialer utillity (Rasdial.exe) to reconnect your VPN.

  3. Create a .bat file and store it in the all users common startup folder
    In order to have this script run when a user logs in, save the following as a batch file 'startvpn.bat' located in 'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp' ; Make sure to change the path to point to the location where you stored the Powershell script from step 2 powershell.exe -executionpolicy bypass -windowstyle hidden -noninteractive -nologo -file "C:\PATHTOYOURPOWERSHELLSCRIPT\autovpn.ps1" This special line in the batch file is needed because most systems have their Powershell ExecutionPolicy set to restricted, and this line in the the batch file set the parameters to intentionally bypass that restriction for this particular powershell script.

  4. Congratulations! You can now double click on that startvpn.bat file and you will always be connected to your VPN. Any users on this system will also always be connected to the VPN as well.