How to script to give back remote desktop to the console? (with tscon and qwinsta)

0

Context

So far I've created a shortcut on my desktop with the following command:

%windir%\System32\tscon.exe 1 /dest:console

It was worked like charm with my old Windows 7 machine, where this active rdp session's id was fixed 1. However the same is not true on my new Windows 10 installation, where it is changing.

I found that that command

 c:\>qwinsta

can give me the active session's ID, so I can replace the number 1 parameter with that. However it seems to be a productivity bottleneck instead just click on an icon.

Question

Is there any way to solve this one script, to somehow get the current active rdp session ID and call tscon with that?

g.pickardou

Posted 2019-08-05T18:38:45.907

Reputation: 224

I would think you could pipe the output from qwinsta to the findstr command looking for "console". the session ID would be 2 tokens from there. poke that into a variable and run your tscon command using the variable instead of the number one. Have you tried this? Is there some reason it cant be done? If you are looking for a 1 liner, that probably can't be done, but your shortcut could call the script... It seems do-able to me. – Larryc – 2019-08-05T19:49:08.417

Thx for the answer, I am gonna try to put this together, although the "poke into a variable" part a bit cloudy for me, but I will google it. – g.pickardou – 2019-08-07T06:29:24.657

Answers

1

Something like this:

@echo off

SETLOCAL ENABLEDELAYEDEXPANSION

for /f "tokens=1-3 delims= " %%a in ('qwinsta^| findstr "console"') do set SessionID=%%c

%windir%\System32\tscon.exe %SessionID% /dest:console

endlocal

When I say "poke it into a variable" thats what I am doing with %SessionID%. I am extracting the session ID number for the console and assigning it to the variable %SessionID%. In the next line I use that variable in the tscon command.

Now all you have to do is create a shortcut to this small script, you should be good to go.

Let me know if you need further explanation.

Larryc

Posted 2019-08-05T18:38:45.907

Reputation: 814

Larry, many thx, I will try it. – g.pickardou – 2019-08-08T16:31:43.353