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:
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:
1 ="1.0"="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><QueryList><Query Id="0"
12 Path="Application"><Select Path="Application"
13 >*[System[Provider[@Name='RasClient'] and EventID=20226]]
14 </Select></Query></QueryList></Subscription>
15 </EventTrigger>
16 <EventTrigger>
17 <Enabled>true</Enabled>
18 <Subscription><QueryList><Query Id="0"
19 Path="Microsoft-Windows-NetworkProfile/Operational">
20 <Select Path="Microsoft-Windows-NetworkProfile/Operational"
21 >*[System[Provider[@Name='NetworkProfile'] and EventID=10000]]
22 </Select></Query></QueryList></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:
1 @echo off
2
3
4 set VPN=My Connection (VPN)
5 set TASK="My Connection (VPN) Redial"
6
7
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:
1 @echo off
2
3
4 set VPN=My Connection (VPN)
5 set TASK="My Connection (VPN) Redial"
6
7
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