Disconnected RDP sessions on a Windows Server consume valuable system resources, memory, and licenses. While group policies can handle session timeouts globally, there are often scenarios where you need a quick, to clean up disconnected sessions—while making sure specific administrative accounts are left untouched.
This guide provides a Batch script using Windows commands (query session and logoff) to automatically identify and log off disconnected sessions while preserving specified admin connections.
The Script
Save the following code as “DisconnectedRDP.bat“
@echo off
setlocal enabledelayedexpansion
rem Logs off ONLY disconnected sessions, except those owned by "admin"
for /f "skip=1 tokens=1-3" %%a in ('query session') do (
rem %%a = USERNAME, %%b = SESSION ID, %%c = STATE (for disconnected sessions)
rem When disconnected, there is no session name column, so the output shifts left.
if /I "%%c"=="Disc" (
set "username=%%a"
set "sess_id=%%b"
rem Check if the user matches the excluded account
echo !username! | find /I "admin" >nul
if errorlevel 1 (
echo Logging off disconnected session ID: !sess_id! ^(User: !username!^)
logoff !sess_id! >nul 2>&1
)
)
)
endlocal
How It Works
- Query Session Output Parsing: When an RDP session is active, query session outputs columns for
SESSIONNAME, USERNAME, ID, and STATE. However, when a session is disconnected, the SESSIONNAME column disappears. - Column Shift Handling: Because the SESSIONNAME column is omitted for disconnected sessions, column values shift to the left:
%%a= Username%%b= Session ID%%c= State (Disc)
- State Verification: The script checks if
%%cequalsDisc(case-insensitive). - Account Exclusion: It uses find /I to check if the session belongs to admin. If errorlevel
1is returned (meaning the target username was not found), the script proceeds to issue the logoff command. - Silent Termination: logoff !sess_id! >nul 2>&1 – terminates the session without printing unnecessary errors or warnings.
Deployment & Automation
To run this script automatically:
- Open Task Scheduler on your Windows Server.
- Create a new task named RDP Session Cleanup.
- Set the task to run under NT AUTHORITY\SYSTEM or a high-privilege administrative account with the option “Run with highest privileges” checked.
- Add a Trigger (e.g., daily, or every 1–2 hours).
- Set the Action to start a program and point to your .bat file.
