Skip to main content

How to Get the RDP Session ID in Batch Script

In modern Windows server management, almost every user action is tied to a Session ID. If you want to log off a user, start an application on their desktop, or shadow their screen, you need to know their unique numerical identifier (e.g., Session 2, Session 14). While you can see this in the Task Manager, a Batch script is the fastest way to programmatically extract the Session ID of the current user or a remote colleague.

This guide explains how to find these IDs.

Why Identify Session IDs?

  • Targeted Logoffs: Removing a specific stuck RDP session without rebooting the entire server.
  • Process Launching: Using tools like psexec to launch a GUI application specifically inside Session 2 so the user can see it.
  • Screen Shadowing: Using mstsc /shadow:3 to view and control another user's screen for technical support.
Console vs. RDP

The "Console" session (physical screen) is usually Session 1 (or simply "Console"). RDP sessions (remote connections) are assigned dynamic IDs (e.g., 2, 3, 4) as users log in.

Method 1: Using 'QUser' for the Current User

The quser command lists the sessions. You can target a specific username to see their session details.

@echo off
echo [PROCESS] Retrieving Session ID for: %USERNAME%...
echo.

quser "%USERNAME%" 2>nul

if %errorlevel% neq 0 (
echo [INFO] No session found for "%USERNAME%".
echo [NOTE] Run as Administrator to see all sessions.
)
pause
endlocal

Method 2: Extracting the ID into a Variable

Since parsing query user columns in pure Batch is unreliable due to column shifting (as documented in companion articles), the most reliable approach uses PowerShell for ID extraction.

@echo off
setlocal

set /p "TARGET=Enter username: "

if "%TARGET%"=="" (
echo [ERROR] No username entered.
pause
exit /b 1
)

echo [PROCESS] Finding session ID for "%TARGET%"...

set "SID="
for /f "tokens=*" %%r in ('powershell -NoProfile -Command ^
"$lines = query user '%TARGET%' 2>$null;" ^
"if ($lines) {" ^
" foreach ($line in ($lines | Select-Object -Skip 1)) {" ^
" if ($line -match '^\s*>?\s*\S+\s+\S+\s+(\d+)') { $Matches[1] }" ^
" elseif ($line -match '^\s*>?\s*\S+\s+(\d+)') { $Matches[1] }" ^
" }" ^
"}" 2^>nul') do (
set "SID=%%r"
)

if defined SID (
echo [SUCCESS] "%TARGET%" is on Session ID: %SID%
) else (
echo [FAIL] User "%TARGET%" is not logged in.
)
pause
endlocal

Creating a Session ID Finder Tool

This professional script provides a complete session lookup with usage examples for the found ID.

@echo off
setlocal EnableDelayedExpansion

echo ============================================================
echo RDP Session ID Locator
echo ============================================================

set /p "USN=Enter Username (or * for all): "

if "!USN!"=="" (
echo [ERROR] No username entered.
pause
exit /b 1
)

:: 1. Show full session info
echo.
if "!USN!"=="*" (
echo [INFO] All current sessions:
) else (
echo [INFO] Session details for "!USN!":
)
echo -----------------------------------------
query user "!USN!" 2>nul
if !errorlevel! neq 0 (
echo User "!USN!" is not logged in.
echo -----------------------------------------
echo.
echo [TIP] Use * to see all sessions.
echo ============================================================
pause
exit /b 1
)
echo -----------------------------------------

:: 2. Extract session IDs using PowerShell for reliability
echo.
echo [RESULT] Session ID(s^):

set "FOUND_ANY=0"
for /f "tokens=1,2" %%a in ('powershell -NoProfile -Command ^
"$lines = query user '!USN!' 2>$null;" ^
"if ($lines) {" ^
" foreach ($line in ($lines | Select-Object -Skip 1)) {" ^
" $user = if ($line -match '^\s*>?\s*(\S+)') { $Matches[1] } else { 'unknown' };" ^
" if ($line -match '^\s*>?\s*\S+\s+\S+\s+(\d+)') { $user + ' ' + $Matches[1] }" ^
" elseif ($line -match '^\s*>?\s*\S+\s+(\d+)') { $user + ' ' + $Matches[1] }" ^
" }" ^
"}" 2^>nul') do (
echo User: %%a ^| Session ID: %%b
set "LAST_ID=%%b"
set "FOUND_ANY=1"
)

if "!FOUND_ANY!"=="0" (
echo Could not extract session IDs.
echo ============================================================
pause
exit /b 1
)

:: 3. Show usage examples with the found ID
echo.
echo [USAGE] You can now use Session ID !LAST_ID! with:
echo logoff !LAST_ID! - Log off this session
echo msg !LAST_ID! "Your message" - Send a message
echo mstsc /shadow:!LAST_ID! /control - Shadow/control the session

echo.
echo ============================================================
pause

Common Pitfalls and How to Avoid Them

Multiple IDs

If the same user has logged in multiple times (e.g., one active session and one disconnected stale session), query user will return multiple lines. Your script must be prepared to handle an array of IDs or simply pick the last one.

Variable "SESSIONNAME"

Windows sets a local environment variable %SESSIONNAME% (e.g., RDP-Tcp#0) for the current user. However, it does not set a %SESSIONID% variable by default in CMD.

SEO and UX Tip

Advise your users that checking %SESSIONNAME% is the fastest way to know if they are in an RDP session (starts with RDP-) or on the physical Console.

Best Practices for Session Management

  1. Use ID for Logoff: Always log off by ID, rarely by name. Logging off by name might kill all sessions for that user, including the one they are currently working in if they have two.
  2. Combine with 'Shadow': Once you have the ID, you can run mstsc /shadow:%ID% /control to instantly view their screen for help desk support.
  3. Audit Services: Remember Session 0 is reserved for services. A user should never have ID 0.
Parsing Reliability

Parsing query user with pure Batch for /f is fragile due to column alignment that varies between console, RDP, and disconnected sessions. The scripts in this guide use PowerShell regex for reliable ID extraction.

Conclusion

Getting the RDP Session ID via Batch script is a fundamental prerequisite for advanced Windows administration. By mastering the query user command and using reliable parsing techniques, you can target specific user sessions for maintenance, support, and security actions with pinpoint accuracy. This professional capability transforms generic user management into precise session control, enabling sophisticated automation workflows across your terminal servers and workstations.