Skip to content

Instantly share code, notes, and snippets.

@brsnik
Last active November 8, 2024 14:48
Show Gist options
  • Save brsnik/bd6ece1c19a08135bd6fb0d561c2f69d to your computer and use it in GitHub Desktop.
Save brsnik/bd6ece1c19a08135bd6fb0d561c2f69d to your computer and use it in GitHub Desktop.
A simple script that will force reconnect your VPN when it disconnects. Optionally it can also send a notification to the user after multiple failed attempts.

VPN Auto Reconnect Script for Windows

1. Setup Your VPN

  1. Open VPN Settings

    • Open the Settings app by pressing Windows + I on your keyboard.

    • Or go to Network & Internet.

  2. Add a VPN Connection

    • Click on VPN on the left-hand side.

    • Click the Add a VPN connection button.

After that, proceed with the usual configuration steps, such as entering the server details, VPN type, and login information.

2. Configure rasphone.exe

Using rasphone fetches the already saved credentials. Unlike rasdial, which requires that credentials be provided.

  1. Locating the .pbk file:

    • For connections saved for the current user:
    C:\Users\%USERNAME%\AppData\Roaming\Microsoft\Network\Connections\Pbk
    
    • system file — for connections saved for all users:
    C:\ProgramData\Microsoft\Network\Connections\Pbk
    
  2. Open rasphone.pbk in any text editor.

  3. Change PreviewUserPw=1 to PreviewUserPw=0. This disables the prompt before dialing.

  4. Then change ShowDialingProgress=1 to ShowDialingProgress=0. This hides the dialing progress window, so the connection process won't be visible.

  5. Finally change ShowMonitorIconInTaskBar=1 to ShowMonitorIconInTaskBar=0. This prevents the monitor icon from appearing in the taskbar when the connection is active.

  6. Save the file.

3. Download/Config Script

Please find the script as files below.

Download and save to a desired folder, that will remain static for the lifetime of the script.

Option 1: vpn_auto_reconn_notify.ps1

With Notifications for Windows 11 and 10

Installs BurntToast if not already installed. For sending out notifications after 10 consecutive failed connection attempts.

  1. Open in any text editor

  2. Change the VPN name $vpnName

  3. You can also localize Send-Notification inside function Check-VpnConnection

  4. Save

Option 2: vpn_auto_reconn.ps1

Compatible with Windows 11, 10, 8 and 7

  1. Open in any text editor

  2. Change the VPN name $vpnName

  3. Save

4. Create a Shortcut

  1. Create a New Shortcut

    • Right-click on the Desktop (or in the folder where you want the shortcut).

    • Select New > Shortcut from the context menu.

  2. Enter the Command

    • In the "Create Shortcut" wizard, you’ll be prompted to type the location of the item.

    • Enter the following command:

    powershell.exe -WindowStyle Hidden -ExecutionPolicy Bypass -File "C:\path\to\script\vpn_auto_reconn_notify.ps1"
    
  • Click Next.
  1. Name the Shortcut

    • Enter a name for your shortcut.

    • Click Finish.

Verify that the shortcut works by running it and checking if the VPN connects.

5. Run on Startup

Simply move the shortcut you just created into one of the following folders.

  • Location for the current user:
C:\Users\%USERNAME%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
  • Location for all users:
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
  • Then Sign out of the current user or restart the computer.

  • And verify that the VPN auto connects:

    • By checking if it connects on login/startup

    • By disconnecting it manually and monitoring for automatic reconnect within ~10-40 seconds

#===============================================================================
# FILE: vpn_auto_reconn.ps1
#
# DESCRIPTION: Automatically force reconnects a VPN.
#
# AUTHOR: Boris Nikk
# VERSION: 1.0.0
# LICENSE: MIT License
#===============================================================================
# Name of the VPN connection
$vpnName = "My VPN"
# Check VPN status frequency in seconds
$checkFrequency = 10
# Function to log messages to the console
function Log-Message {
param (
[string]$message
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Write-Host "$timestamp - $message"
}
# Function to check VPN status and reconnect if necessary
function Check-VpnConnection {
try {
$conn = (Get-VpnConnection -Name $vpnName).ConnectionStatus
if ($conn -eq 'Disconnected') {
rasphone -d $vpnName
Log-Message "VPN disconnected. Attempting to reconnect..."
Start-Sleep -Seconds 30 # Delay to allow connection to stabilize
}
}
catch {
Log-Message "Error checking VPN status or reconnecting: $_"
}
}
# Main loop
while ($true) {
Check-VpnConnection
Start-Sleep -Seconds $checkFrequency
}
#===============================================================================
# FILE: vpn_auto_reconn_notify.ps1
#
# DESCRIPTION: Automatically force reconnects a VPN and will send a notification after multiple failed attempts.
#
# AUTHOR: Boris Nikk
# VERSION: 1.0.0
# LICENSE: MIT License
#===============================================================================
# Name of the VPN connection
$vpnName = "My VPN"
# Check VPN status frequency in seconds
$checkFrequency = 10
# Maximum allowed failed connection attempts before alerting
$maxFailedAttempts = 10
# Counter for failed attempts
$failedAttempts = 0 # DO NOT MODIFY
# Function to log messages to the console
function Log-Message {
param (
[string]$message
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Write-Host "$timestamp - $message"
}
# Function to ensure BurntToast is installed
function Ensure-BurntToastInstalled {
if (-not (Get-Module -ListAvailable -Name BurntToast)) {
Log-Message "BurntToast module not found. Installing..."
Install-Module -Name BurntToast -Force -Confirm:$false -Scope CurrentUser
Import-Module BurntToast
Log-Message "BurntToast module installed successfully."
} else {
Import-Module BurntToast
}
}
# Function to send a toast notification using BurntToast
function Send-Notification {
param (
[string]$title,
[string]$message
)
New-BurntToastNotification -Text $title, $message -Sound "Alarm2" -AppLogo "C:\fake.png" # Pointing at a non-existent image, you'll get a warning
}
# Function to check VPN status and reconnect if necessary
function Check-VpnConnection {
try {
$conn = (Get-VpnConnection -Name $vpnName).ConnectionStatus
if ($conn -eq 'Disconnected') {
rasphone -d $vpnName
Log-Message "VPN disconnected. Attempting to reconnect..."
$failedAttempts++
Start-Sleep -Seconds 30 # Delay to allow connection to stabilize
# Send a notification if maximum failed attempts reached
if ($failedAttempts -ge $maxFailedAttempts) {
Send-Notification "VPN Connection Issue" "Failed to connect to $vpnName after $failedAttempts attempts."
$failedAttempts = 0 # Reset the counter after notifying
}
} else {
$failedAttempts = 0 # Reset the counter on successful connection
}
}
catch {
Log-Message "Error checking VPN status or reconnecting: $_"
}
}
# Ensure BurntToast module is installed
Ensure-BurntToastInstalled
# Main loop
while ($true) {
Check-VpnConnection
Start-Sleep -Seconds $checkFrequency
}
@Nareese
Copy link

Nareese commented Nov 8, 2024

Thanks for the quick response.

I am on Win11. My VPN connection is set up through the standard Win11 VPN setup in the Settings panel, my credentials are entered there, and are configured to be saved there, and thus rasdial does not require them to be supplied on the command line. Only the connection name is required. Also probably worthy of note, when rasphone pops the connect dialog, the saved credentials, both username and password, are pre-filled in the dialog, so I just have to hit connect, so it's definitely picking up the correct connection. I did check that it was not a system vs user issue, as the system config directory is empty. So as I said, no clue what's going on there, it should be working. Regardless, rasdial works great for me, it was more just an FYI for you and others in case someone else runs into this weirdness.

@brsnik
Copy link
Author

brsnik commented Nov 8, 2024

@Nareese Thanks for the additional info. The reason I avoided rasdial was it asking for credentials. But what you're describing is that it works as desired. The scripts were originally developed on Win 10, so maybe there are changes in 11. I'm gonna have to investigate this further and post an update.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment