Using the correct session id can indeed be necessary to adequately start a job on a remote machine that is accessed by several distinct users.
Here's what I found after tinkering with a combination of batch commands and psexec. I rolled it all in a *.bat file taking 4 parameters: (P1)UserName, (P2)ServerName, (P3)Login, (P4)Password.
After execution (and if successful), the session info is simply stored in 4 variables: (V1)SessionName, (V2)SessionUser, (V3)SessionId, (V4)SessionState.
The batch is designed for remote info access, but can easily be adapted to local usage.
@echo off
REM This program gets remote session info on a given server, for a given user.
REM It needs 4 parameters: UserName, ServerName, Login, Password
REM For a local session, simply replace the 'psexec \\...' command parsed by the 'for'
REM loop with: 'query session ^| find /i "%UserName%"'
REM In that case, only the UserName parameter is necessary to call this batch.
set UserName=%1
set ServerName=%2
set Login=%3
set Password=%4
set SessionName=
set SessionUser=
set SessionId=
set SessionState=
for /f "tokens=1,2,3,4 delims=^> " %%a in ('psexec \\%ServerName% -u %Login% -p %Password% query session ^| find /i "%UserName%"') do (
REM Test iterator because a disconnected session may no longer have a name!
if /I "%%b"=="%UserName%" (
set SessionName=%%a
set SessionUser=%%b
set SessionId=%%c
set SessionState=%%d
)
if /I "%%a"=="%UserName%" (
set SessionName=[unknown]
set SessionUser=%%a
set SessionId=%%b
set SessionState=%%c
)
)
echo Session info:
echo - Name: %SessionName%
echo - User: %SessionUser%
echo - ID: %SessionId%
echo - State: %SessionState%
NOTES:
- The loop delimiters are '>' and 'space'. That's because the 'query session' command output contains a '>' to indicate the active session on the targeted machine. I had to find a way for the loop to ignore this troublesome character, as it is normally interpreted as redirection to a file.
- I voluntarily ignored the session type and device outputs. I believe they could eventually be added using %%e and %%f to feed 2 more variables in the loop if need be.
- As explained in the batch comment, to use the batch on the local machine you shouldn't use the 'psexec \\...' call but: 'query session ^| find /i "%UserName%"' instead. In that case, only parameter P1 is needed.
2It doesn't require a session ID in the sense that it simply defaults to 0, but that default is useless if there are multiple users logged in and you want to pick a specific one. – user1686 – 2013-07-01T16:53:56.470