Restore console session after remote desktop disconnects?

Create a batch file with the following contents, named something like restore_console.bat:

@echo off
set LOG_FILENAME=%TEMP%\restore_console_log.txt
echo Script executed at %TIME% > %LOG_FILENAME%
echo qwinsta: >> %LOG_FILENAME%
qwinsta >> %LOG_FILENAME%

echo Checking for pending connection... >> %LOG_FILENAME%
for /f %%i in ('qwinsta ^| findstr /r /C:"^ [ ]*[0-9][0-9]*  Disc"') do (
echo Pending connection detected, finishing. >> %LOG_FILENAME%
goto end
)

echo Checking for disconnection... >> %LOG_FILENAME%
for /f "tokens=2" %%i in ('qwinsta ^| findstr /r /I /C:"^ [ ]*[^ ][^ ]* [ ]*[0-9][0-9]*  Disc"') do (
echo Redirecting session id %%i >> %LOG_FILENAME%
tscon %%i /dest:console /v >> %LOG_FILENAME%
goto end
)

:end

In Task Scheduler, create a new task, with the following settings:

  • General -> Run whether user is logged on or not, Run with Highest privileges.
  • Triggers -> New -> On disconnect from user session, Any user, Connection from remote computer
  • Actions -> New -> Start a program -> Program/script: <your batch file>
  • Everything else default.

Notes regarding implementation:

  • this works by parsing the qwinsta output through a findstr regex, i.e. extracting the ID from line 3 here:

     SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE 
    >services                                    0  Disc                        
                       ######                    2  Disc                        
     console                                     7  Conn                        
     #############...                        65536  Listen                      
     rdp-tcp                                 65537  Listen                      
    
  • the middle block is necessary because for some reason the schedule task executes on connection as well as disconnection. When this happens, the output will be of the form:

     SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE 
    >services                                    0  Disc                        
                       ######                    2  Disc                        
                                                 3  Disc                        
     console                                     8  Conn                        
     #############...                        65536  Listen                      
     rdp-tcp                                 65537  Listen                      
    

    Therefore we look for lines of the pattern from line 4.

  • it dumps logging information to %TEMP%\restore_console_log.txt, which is not necessary, but useful if the script doesn't work. Without the logging it would be only a few lines.

This worked for me on a single Windows 8.1 machine - I don't know if it could be rolled out globally.