Logoff Disconnected Users From Remote Desktop via batch-file

Posted on .

I would like to log-off some users after they have disconnected. Windows has this feature built-in, you can find it at the user-properties “Sessions” tab.

However I have found this feature to be unreliable. Whether it is set to log-off disconnected users at 1 minute or 5 minutes, during isolated tests it works fine, but when in production it has failed multiple times in the last few months with disconnected sessions lingering for hours before noticed.

I found this command-line code to log-off all disconnected users. It seemed to fit the purpose. It uses “quser” to get the list of logged on users, writes them to a file, finds the ones that are disconnected and uses “rwinsta” to log them off. Pretty neat.

I felt I could improve on it though. I saw it didn’t really need to write to a temporary file, and just use internal variables. I also wanted it to connect to multiple servers and be able to list specific users to be logged off.

This can then be added to an elevated scheduled task that runs every X minutes to check for disconnected users.

This is working for Windows Server 2008 R2 and Windows Server 2012.

Disconnect listed users:
(adjust the list of servers and users)

Disconnect all users:
(adjust the list of servers)

6 thoughts on “Logoff Disconnected Users From Remote Desktop via batch-file

  1. John Salfer

    Awesome batch file. Very much appreciate your posting it. Saved a lot of time and frustration of creating it myself.

    Reply
  2. Anonymous

    @echo off
    query session >xx.txt
    timeout2
    FIND /V “Active” xx.txt >result.txt
    timeout4
    FIND /V “Conn” result.txt >result2.txt
    timeout3
    FIND /V “Listen” result2.txt >result3.txt
    timeout3
    FOR /F “skip=8 tokens=2,” %%i IN (result3.txt) DO logoff %%i

    Reply

Leave a Reply

You may leave the Name and Email fields blank to post anonymously.