Keeping an active desktop session

Credit: this post heavily uses/reuses the content from Arnon Axelrod’s post. For some reasons, I couldn’t leave him a comment because of reCAPTCHA issue. So I decided to create this post and cover part he didn’t. I strongly recommend you to visit his post for full story.

Some test automation tools require an active desktop session to operate normally. I have been struggling with other approaches: autologin, relogin, unlock locked screen, etc. All of them led to same dead end. I already have a post for “How To Unlock Desktop Screen After Remote Access Disconnected” however it requires running cmd command as administrator which is not so convenience.

What locks the desktop?
1. System locked (Windows Key + L) – So far, I don’t see any better solution than using VNC.
2. Remote Desktop session disconnected – See solution below

In my opinion, Arnon Axelrod’s approach or solution is so elegent for this very common test automation problem. What we need to do is keeping an active desktop session by getting cmd command triggered automatically upon RDC disconnected.

In brief, the solution is composed of few pieces
1. A Task Scheduler’s task that is triggered upon disconnecting form Remote Desktop
2. The query session command
3. The TSCon command
4. A windows script that combines the 2 commands

for /f “skip=1 tokens=2” %s in (‘query user %USERNAME%’) do (tscon.exe %s /dest:console)

How To Unlock Desktop Screen After Remote Access Disconnected

Remote Desktop to VM to check out, investigate issues, deploy things are very common, especially when you are in CI/CD, Agile, DevOps environment. The demand to unlock desktop screen remotely is crucial for automation tests to run. A friend of mine says he struggled with this for 2 weeks. Therefore I am going to put simple and short answer right below.

How To Unlock Desktop Screen Remotely

Please note that you need to run these commands with administrative rights on remote machine.

Below command should work for Windows 7, Windows 8, Windows 8.1, Windows 10

tscon [RDC Session ID] /dest:console
Ex. tscon 1 /dest:console

Session ID can be retrieve by issuing below command

query session

Or simply use below single command

for /f "skip=1 tokens=2" %%s in ('query user %USERNAME%') do (
    tscon.exe %%s /dest:console


Below command should work on Windows Server

tscon %sessionname% /dest:console

If you have PowerShell installed on your remote machine, try this one

tscon ((quser $env:_TFSLab | select -Skip 1) -split '\s+')[2] /dest:console

Wrapping Up

That’s it. It’s simple when you know it and it can take you weeks if you don’t (like my friend’s case). Please share if you have any inputs or comment if these work for you.