Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / XML
Tip/Trick

Reconnect Windows 10 VPN Automatically

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
5 May 2020CPOL4 min read 38.5K   829   6   7
Use Windows 10 build-in tools to configure VPNs for automatic reconnection after a connection is lost
This tip is about how to setup a VPN connection and reconnect with the task scheduler. You will learn about activation, connection, disconnection and deactivation of the VPN connection.

Introduction

During Corona times, home office becomes more and more important. Company’s resources are accessed by Virtual Private Networks (VPN). When using the build-in Windows VPN Client for PPTP, L2TP/IPSec, SSTP or IKEv2, connections are not reestablished automatically if the connection is lost. A VPN interruption might be caused by a change of the network or Internet network error.

In the everyday life of home workers and road warriors, a drop of a VPN connection leads to hectic activity, because remote desktop clients stop at first and then try to reconnect. The file explorer gets stuck and then tries to display server shares desperately. With a quick click, the experienced power user tries to reconnect the VPN before all applications say goodbye with a timeout error message and all programs have to be restarted. However, this does not succeed in all cases...

For these circumstances, Microsoft simply forgot the feature of an automatic reconnection for VPN connections. Probably, there is always somewhere a checkbox which is missing desperately...

Configuration and Script Code

VPN Connection Setup

To configure the automatic reconnection of a VPN, user name and password must be stored in the Windows Credential Manager. This behavior is specified during the setup:

Image 1

If the option "Remember my credentials" is checked, Windows will save the user name and password after the first connection of the VPN.

Reconnection with the Task Scheduler

Then, the reconnect VPN feature can be configured with build-in Windows tools. Starting point are the Windows event logs in which the following events occur:

Event Id Source Description
20226 RasClient ROUTERLOG_CORR_ID = The user %1 () dialled a connection named %2 () which has been terminated. The reason code returned on termination is %3 ().
10000 NetworkProfile Network connected.

Event 2226 occurs when a VPN connection has been terminated. In this case, an attempt is made to reconnect the VPN immediately. If the reconnection fails, the events 10000 and 8001 trigger a reconnection in the case of a new wired or WiFi network connection of the client.

A task can be imported as "My Connection (VPN) Redial.xml" with an XML format into the Task Scheduler and executed with the logged in user account:

XML
  1  <?xml version="1.0" encoding="UTF-16"?>
  2  <Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  3    <RegistrationInfo>
  4      <Date>2020-04-11T09:32:43.9830717</Date>
  5      <Author>LOGICLINK\marcus</Author>
  6      <URI>\My Connection (VPN) Redial</URI>
  7    </RegistrationInfo>
  8    <Triggers>
  9      <EventTrigger>
 10        <Enabled>true</Enabled>
 11        <Subscription>&lt;QueryList&gt;&lt;Query Id="0" 
 12         Path="Application"&gt;&lt;Select Path="Application"
 13         &gt;*[System[Provider[@Name='RasClient'] and EventID=20226]]
 14         &lt;/Select&gt;&lt;/Query&gt;&lt;/QueryList&gt;</Subscription>
 15      </EventTrigger>
 16      <EventTrigger>
 17        <Enabled>true</Enabled>
 18        <Subscription>&lt;QueryList&gt;&lt;Query Id="0" 
 19         Path="Microsoft-Windows-NetworkProfile/Operational"&gt;
 20         &lt;Select Path="Microsoft-Windows-NetworkProfile/Operational"
 21         &gt;*[System[Provider[@Name='NetworkProfile'] and EventID=10000]]
 22         &lt;/Select&gt;&lt;/Query&gt;&lt;/QueryList&gt;</Subscription>
 23      </EventTrigger>
 24    </Triggers>
 25    <Principals>
 26      <Principal id="Author">
 27        <LogonType>InteractiveToken</LogonType>
 28        <RunLevel>LeastPrivilege</RunLevel>
 29      </Principal>
 30    </Principals>
 31    <Settings>
 32      <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
 33      <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
 34      <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
 35      <AllowHardTerminate>true</AllowHardTerminate>
 36      <StartWhenAvailable>false</StartWhenAvailable>
 37      <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
 38      <IdleSettings>
 39        <StopOnIdleEnd>true</StopOnIdleEnd>
 40        <RestartOnIdle>false</RestartOnIdle>
 41      </IdleSettings>
 42      <AllowStartOnDemand>true</AllowStartOnDemand>
 43      <Enabled>false</Enabled>
 44      <Hidden>false</Hidden>
 45      <RunOnlyIfIdle>false</RunOnlyIfIdle>
 46      <DisallowStartOnRemoteAppSession>false</DisallowStartOnRemoteAppSession>
 47      <UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>
 48      <WakeToRun>false</WakeToRun>
 49      <ExecutionTimeLimit>PT72H</ExecutionTimeLimit>
 50      <Priority>7</Priority>
 51    </Settings>
 52    <Actions Context="Author">
 53      <Exec>
 54        <Command>%SystemRoot%\System32\rasdial.exe</Command>
 55        <Arguments>"My Connection (VPN)"</Arguments>
 56      </Exec>
 57    </Actions>
 58  </Task>

In line 55, the name of the VPN connection must be changed to the name of your VPN connection. The VPN connection should have been established manually with user and password before the first use. Thus, credentials do not have to be entered as parameters for rasdial.exe and stored in the task.

Furthermore, the task should be deactivated by default and only activated when the VPN is needed, thereby it does not establish VPN connections and consume bandwidth unnecessarily.

Activation and Connection of the VPN

The activation and deactivation are done by two batch programs:

The batch file "Enable My Connection (VPN).cmd" activates the task for automatic reconnection and then connects the VPN:

BAT
  1  @echo off
  2  
  3  :: REMARKS: Don't use double quotes for VPN name as they've to be escaped by back slashes for runas
  4  set VPN=My Connection (VPN)
  5  set TASK="My Connection (VPN) Redial"
  6  
  7  :: Check for administrative rights
  8  net session >nul 2>&1
  9  if NOT %errorLevel% == 0 (
 10  	echo Current permissions insufficient. Run script as administrator.
 11  	pause
 12  	exit 1
 13  )
 14  
 15  schtasks /Change /TN %TASK% /ENABLE
 16  runas /trustlevel:0x20000 "rasdial.exe \"%VPN%\""

In lines 4 and 5, the two variables VPN and TASK identify the VPN connection and the task of the Task Scheduler and must be changed to your individual names accordingly. Using these variables, you can configure multiple batch files for several VPNs.

In the next step, the batch file checks if it was started with administrative rights. The administrative rights are required for the activation of tasks in Task Scheduler. If the batch file was not “Run as administrator”, an error message is displayed and the batch file terminates.

Next, the task TASK is activated in the Task Scheduler. For the connection of the VPN with stored credentials, administrative rights have to be returned. Thus, rasdial.exe is called via runas.exe with user rights by the trustlevel 0x20000.

Disconnection and Deactivation of the VPN Connection

The deactivation and disconnection is done in the batch file "DisableMy Connection (VPN).cmd" by the same commands:

BAT
  1  @echo off
  2  
  3  :: REMARKS: Don't use double quotes for VPN name as they've to be escaped by back slashes for runas
  4  set VPN=My Connection (VPN)
  5  set TASK="My Connection (VPN) Redial"
  6  
  7  :: Check for administrative rights
  8  net session >nul 2>&1
  9  if NOT %errorLevel% == 0 (
 10  	echo Current permissions insufficient. Run script as administrator.
 11  	pause
 12  	exit 1
 13  )
 14  
 15  schtasks /Change /TN %TASK% /DISABLE
 16  rasdial "%VPN%" /DISCONNECT

The two variables VPN and TASK in lines 4 and 5 must be changed according to your names also. During the termination of the VPN connection, the administrative rights do not interfere and therefore, rasdial.exe can be called directly.

References

History

  • 4th May, 2020: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder LogicLink
Germany Germany
In the early 1980s I stumbled across a Zilog Z80 in the form of a ZX80 and found my programming passion. From Assembler and Basic to Pascal and Turbo Pascal, C, C++ and Java, Javascript and CSS after years of Visual Basic and SQL I ended up with C#, XAML, T-SQL and ASP.Net, coquetting with F#.

I graduated from University of Cologne in molecular biology combining bio science and computer engineering. Since 1996 I founded my own company working on Windows and web-based software for laboratories and other businesses with Microsoft technologies.

My Website:

https://www.logiclink.de

Comments and Discussions

 
QuestionSetting AutoLogon to 1 Pin
Peter Vroegindewey20-Jan-21 20:21
Peter Vroegindewey20-Jan-21 20:21 
QuestionMessage Closed Pin
23-Sep-20 2:01
floflo7723-Sep-20 2:01 
QuestionUnable to reconnect with certificate based VPN client Pin
Member 460414419-Aug-20 10:29
Member 460414419-Aug-20 10:29 
AnswerRe: Unable to reconnect with certificate based VPN client Pin
johnnyys10-Sep-20 1:32
professionaljohnnyys10-Sep-20 1:32 
QuestionConnection and disconnection scripts Pin
PatriceBG5-May-20 9:27
PatriceBG5-May-20 9:27 
AnswerRe: Connection and disconnection scripts Pin
Marcus Müller5-May-20 22:51
professionalMarcus Müller5-May-20 22:51 
SuggestionI would use it if I needed to Pin
Mark I5-May-20 4:51
Mark I5-May-20 4:51 
GeneralRe: I would use it if I needed to Pin
Marcus Müller5-May-20 22:53
professionalMarcus Müller5-May-20 22:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.