Search code examples
windowsbatch-fileskype

How to get (interactive) session # of known username in batch


I've discovered how to list the sessions in Windows, I get the following output from either...

c:\logonsessions -c

Logonsessions v1.3
Copyright (C) 2004-2015 Mark Russinovich
Sysinternals - wwww.sysinternals.com

Session,User Name,Auth Package,Logon Type,Session,Sid,Logon Time,Logon Server,DNS Domain,UPN,Processes
00000000:000003e7,WORKGROUP\pcname$,NTLM,(none),0,S-1-5-18,9/19/2015 2:51:11 PM,,,,
00000000:0000a5ea,,NTLM,(none),0,(none),9/19/2015 2:51:11 PM,,,,
00000000:000003e4,WORKGROUP\pcname$,Negotiate,Service,0,S-1-5-20,9/19/2015 2:51:15 PM,,,,
00000000:000003e5,NT AUTHORITY\LOCAL SERVICE,Negotiate,Service,0,S-1-5-19,9/19/2015 2:51:15 PM,,,,
00000000:000003e3,NT AUTHORITY\IUSR,Negotiate,Service,0,S-1-5-17,9/19/2015 2:51:29 PM,,,,
00000000:000237ce,NT AUTHORITY\ANONYMOUS LOGON,NTLM,Network,0,S-1-5-7,9/19/20152:51:40 PM,,,,
00000000:0008f3b8,pcname\targetuser,NTLM,Interactive,3,S-1-5-21-619702857-3907507909-453961168-1000,9/19/2015 3:13:18 PM,D,,,
00000000:000c0c9d,IIS APPPOOL\siteA,Negotiate,Service,0,S-1-5-82-2579537164-80563901-952080054-1630798588-2545742339,9/19/2015 3:31:45 PM,,,,
00000000:001df99a,IIS APPPOOL\siteB,Negotiate,Service,0,S-1-5-82-3368103016-2489489752-2714024436-2368677762-3860426159,9/19/2015 5:16:52 PM,,,,

or

c:\query session
 SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE
                                             0  Disc
>console           targetuser                3  Active
 rdp-tcp                                 65536  Listen

So if the known username is "targetuser" then per above the session ID is 3.

How can I read/parse this to get the session number? I anticipate it won't always be "3" in the future. The other option is to rely on whatever is the console user, cause there can only be one right? (user switching is NOT enabled on this workstation) and return the session number of the console user.

Why do I care about the session #? cause I need to run something that will prompt the user on the workstation if they want to do it now, or not.

When I launch this process via...

psexec -accepteula -i 3 -d "C:\Program Files (x86)\Skype\Phone\Skype.exe" /callto:[user_ID]

...I must be able to supply the session ID (in this case 3)

Edit: Apparently, this might be easier...

c:\query session targetuser
SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE
>console          targetuser                3  Active

...so that's already closer to what I want, now I just have to parse the second line to find the ID (in this case "3") and store it as a variable.


Solution

  • for /f "tokens=3 skip=1" %%# in ('qwinsta targetuser') do set "userid=%%#"
    echo %userid%
    

    Mind that qwinsta/query/terminal services are not installed on home/basic editions of windows.