Log Off Disconnected Remote Desktop (RDP) Sessions via Batch Script

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

  1. 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.
  2. 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)
  3. State Verification: The script checks if %%c equals Disc (case-insensitive).
  4. Account Exclusion: It uses find /I to check if the session belongs to admin. If errorlevel 1 is returned (meaning the target username was not found), the script proceeds to issue the logoff command.
  5. Silent Termination: logoff !sess_id! >nul 2>&1 – terminates the session without printing unnecessary errors or warnings.

Deployment & Automation

To run this script automatically:

  1. Open Task Scheduler on your Windows Server.
  2. Create a new task named RDP Session Cleanup.
  3. Set the task to run under NT AUTHORITY\SYSTEM or a high-privilege administrative account with the option “Run with highest privileges” checked.
  4. Add a Trigger (e.g., daily, or every 1–2 hours).
  5. Set the Action to start a program and point to your .bat file.

********************************************************

If you liked what you read Please Share.
I’d love it if you followed me on YouTube and Facebook.

Also, feel free to subscribe to my posts by email.
Donations for the site can be made here.
Thanks for reading.

Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *