30

How can I retrieve the current user session ID via windows command line?

In the tasklist under the users tab, each user is associated with a session ID. I want to retrieve this via command line so I can use it for a remote application.

5
  • I'm not sure what you mean by session ID? – EBGreen Jun 29 '11 at 14:19
  • In the tasklist under the users tab, each user is associated with a session ID. I want to retrieve this via command line so I can use it for a remote application. – Negative Jun 29 '11 at 14:30
  • also see superuser.com/questions/123242/… – matt wilkie Dec 20 '12 at 18:45
  • %%G would be if you call it from a batch, %G if directly from the command line – user449327 May 18 '15 at 16:05
  • 1
    If you can now use Powershell, see stackoverflow.com/a/30103072/868159 – oatsoda Feb 18 '20 at 8:56
33

This is certainly not the most efficient way, but you can take a look at the results of tasklist. It will display the name and session# of each process running. If you are logged in locally then look at the ID for the session named "console".

d:\>tasklist

Image Name                     PID Session Name        Session#    Mem Usage
========================= ======== ================ =========== ============
System Idle Process              0 Services                   0         24 K
System                           4 Services                   0      8,580 K
smss.exe                       316 Services                   0      1,500 K
...snip

Edit:

Query Session will retrieve the session id:

d:\>query session
 SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE
 services                                    0  Disc
>console           janedoe                   1  Active
 rdp-tcp                                 65536  Listen
5
  • I'm looking to retrieve it via command line. – Negative Jun 29 '11 at 14:29
  • 1
    Right, from the command line, type tasklist. – Gary Jun 29 '11 at 14:30
  • 1
    Hmm actually you might be on to something here. edit: tasklist /FI "imagename eq cmd.exe" /FO list I plan on parsing this output. Thanks! – Negative Jun 29 '11 at 14:35
  • Or I can do that. Nice – Negative Jun 29 '11 at 14:36
  • 1
    tasklist is good because it doesn't require a Pro/Ent OS version. You can also list only interactive sessions by filtering for explorer.exe - tasklist /fi "imagename eq explorer.exe" – shawn Dec 27 '18 at 18:23
9

This combines aspects of Gary’s answer and Oscar’s answer.  As noted by Gary, the output of query session looks something like

 SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE
 services                                    0  Disc
>console           janedoe                   1  Active
 rdp-tcp                                 65536  Listen

or, in my case (using “Switch user”)

 SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE
 services                                    0  Disc
>console           gman                      1  Active
                   otherguy                  2  Disc

(I don’t have RDP set up, so I can’t test with it.)  Presumably the intent of the question is to determine the ID of the currently active session.  I suggest searching the output of query session for what looks like the current session:

 for /f "tokens=2-4" %a in ('query session') do @if "%a"=="%username%" if "%c"=="Active" echo %b

which assigns the 2nd, 3rd, and 4th word (which we hope to be the USERNAME, [SESSION] ID, and STATE) from each line of the output of query session to %a, %b, and%c, respectively, and then reports SESSION ID from the line where USERNAME is me and STATE is Active.

It turns out that query session takes a username parameter, so the above can be simplified to

 for /f "tokens=2-4" %a in ('query session %username%') do @if "%c"=="Active" echo %b

or

for /f "tokens=3-4" %a in ('query session %username%') do @if "%b"=="Active" echo %a

To use this in a script (batch file), you might want to say

set MY_SESSION_ID=unknown
for /f "tokens=3-4" %%a in ('query session %username%') do @if "%%b"=="Active" set MY_SESSION_ID=%%a

using %%a and %%b (instead of %a and %b) because it’s in a script.  You can probably leave out the @ if the entire batch file is under @echo off. The initialization to unknown lets you do error-handling (detecting if there is no line in the output of query session that matches).  Extending the error-handling to recognize and react if there are multiple matching lines in the output of query session is left as an exercise.

3
  • In my real-world case, if there are multiple sessions, they will always have the same username. But this probably not typical. – Matthew Lundberg Feb 5 '16 at 0:52
  • @MatthewLundberg: How about STATE? Are sessions other than the current one identified as "Active"? – G-Man Says 'Reinstate Monica' Feb 5 '16 at 3:16
  • Yes, they would be active. It is a server OS. – Matthew Lundberg Feb 5 '16 at 3:50
5
for /f "tokens=4 delims= " %%G in ('tasklist /FI "IMAGENAME eq tasklist.exe" /NH') do SET RDP_SESSION=%%G
echo Current RDP Session ID: %RDP_SESSION%
3
  • 1
    Oscar's solution actually worked for me, when replaced %%G with %G: for /f "tokens=4 delims= " %G in ('tasklist /FI "IMAGENAME eq tasklist.exe" /NH') do SET RDP_SESSION=%G – Paweł Stankowski Jan 15 '15 at 10:53
  • 2
    @PawełStankowski: that's the difference if you run it from a batch file (%%) or from console (%) – Thomas Weller Sep 4 '15 at 9:07
  • Note that this breaks in the unlikely event that multiple users are running tasklist at the same time. – Matthew Lundberg Feb 4 '16 at 22:05
2

Unlike the Session Name, the Session ID is not stored in a variable and is not as easy to get to. I am sure there is one, but I can't think of a built in command line tool that does this.

However, I have written a tiny .exe file (C#, .Net 4) that does this.

It will both display the session id, and also have it as the return code so that you can use this in a variety of scripts/techniques.

Link to file on MediaFire

0
1

This is based on the code from Oscar Beh.

tasklist will show report the session ID (and other information) for all instances of a given executable, including itself. As you're running the command, it will show your session id. The only potential defect in his code is that it does not inform you if there are multiple instances of the program, which can cause the script to return incorrect results.

Here we report all instances of tasklist to ensure that there is not another session running that command:

for /f "tokens=4 delims= " %%G in ('tasklist /FI "IMAGENAME eq tasklist.exe" /NH') do echo Session ID %%G

If you see two Session ID's reported, run the script again.

0
tasklist | find /I "conhost.exe"

returns output like

conhost.exe                   8008 Console                   10      5,848 K
conhost.exe                  13352                           11      5,712 K

The column headers are:

Image Name                     PID Session Name        Session#    Mem Usage
========================= ======== ================ =========== ============

Active sessions have a name, inactive sessions have a blank name.

So the following looks for the 'K' in the last column. The row that holds the answer has a session name whereas other lines will have one less column and no 'K' in column 6.

for /f "tokens=4-6" %G in ('tasklist ^| find /I "conhost.exe"') do @if "%I"=="K" set MY_SESSION_ID=%G

If using it from inside a batch file:

for /f "tokens=4-6" %%G in ('tasklist ^| find /I "conhost.exe"') do @if "%%I"=="K" set MY_SESSION_ID=%%G

Not the answer you're looking for? Browse other questions tagged or ask your own question.