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)
1 2 3 4 5 6 7 8 9 10 11 12 |
@ECHO off rem Logs off disconnected users listed in "%users%" SETLOCAL SET "users=joe jane geoff" SET "servers=rds1 rds2 rds3" FOR %%s IN (%servers%) DO ( FOR /f "tokens=1,2" %%a IN ('"Quser /server:%%s | findstr Disc"') DO ( FOR %%n IN (%users%) DO ( IF /I %%a==%%n rwinsta /server:%%s %%b ) ) ) |
Disconnect all users:
(adjust the list of servers)
1 2 3 4 5 6 7 8 9 |
@ECHO off rem Logs off all disconnected users SETLOCAL SET "servers=rds1 rds2 rds3" FOR %%s IN (%servers%) DO ( FOR /f "tokens=2" %%a IN ('"Quser /server:%%s | findstr Disc"') DO ( rwinsta /server:%%s %%a ) ) |
Awesome batch file. Very much appreciate your posting it. Saved a lot of time and frustration of creating it myself.
Excellent! Thank you very much.
super thx – it works
Big Thanks!
Thanks a lot!
@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
How can we use the script to logoff disconnected session ideal from 2 hours
works perfect!
Could someone help me with this:
in that code, how can i add/insert some line(s) to change Registry for each user disconnected?
Someting like:
Reg.exe add “HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced” /v “PersistBrowsers” /t REG_DWORD /d “0” /f
before log off user. (rwinsta /server:%%s %%a)
Tanks Regards