batch-filewindows-server-2012-r2remote-desktop

Script to Kill All RDP Sessions


I am trying to create a simple script to kill ALL remote desktop sessions, active or disconnected, without rebooting the server. My server OS is Windows Server 2012R2 with Remote Desktop Services enabled and licensed.

I found a simple batch file script here to do this task: enter link description here

When I run this script locally on my terminal server, I get an error in the batch file runs that says: Session Disc not found

And only the console user is logged off. Can anyone tell me what is wrong with this script?

query session >session.txt
for /f "skip=1 tokens=3," %%i in (session.txt) DO logoff %%i
del session.txt

My Session text file looks like this:

 SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE 
 services                                    0  Disc                        
 >console           Administrator            13  Active                      
                   wcunningham              18  Disc                        
                   kstarkey                 25  Disc                        
 rdp-tcp#11        cyannone                 52  Active                      
 rdp-tcp                                 65536  Listen                      

Solution

  • What I found is a good workaround is adding an additional line to handle the disconnected sessions. Since disconnected sessions don't list the sessionname, the ID is at position 2 not position 3 like it is with active session. So adding an additional line that specifies token=2 did the trick:

    query session >session.txt
    for /f "skip=1 tokens=2," %%i in (session.txt) DO logoff.exe %%i
    for /f "skip=1 tokens=3," %%i in (session.txt) DO logoff.exe %%i
    del session.txt