• 2 Posts
  • 617 Comments
Joined 2 months ago
cake
Cake day: May 9th, 2024

help-circle


  • It provides correct answers.

    I will give you an example, this was for a recent project we had with a machine that requires to be connected to the internet at all times through a VPN connection.

    How to setup Windows VPN to automatically reconnect after connection loss using PowerShell?

    Using PowerShell Script
    Create a PowerShell Script to Monitor and Reconnect VPN:
    
    Open Notepad and paste the following script:
    In powershell
    
    $vpnName = "Your_VPN_Connection_Name"
    $username = "your_username"
    $password = "your_password"
    
    while ($true) {
        $vpnConnection = Get-VpnConnection -Name $vpnName
        if ($vpnConnection.ConnectionStatus -ne "Connected") {
            rasdial $vpnName $username $password
        }
        Start-Sleep -Seconds 60
    }
    Replace $vpnName, $username, and $password with your VPN connection details.
    Save this file with a .ps1 extension, e.g., vpn_reconnect.ps1.
    Set Up Task Scheduler to Run the PowerShell Script:
    
    Follow the same steps as in Method 2, but when selecting the program to start, use powershell.exe and add the script path as an argument.
    Example: powershell.exe -File "C:\path\to\your\vpn_reconnect.ps1"