Automatically log off disconnected RDP sessions with PowerShell

Here is a PowerShell script I use to log off disconnected sessions. When a user closes its connection and forget to actually use the Sign out button on Windows, all the programs he was using are still running and using resources. You can use this little script to configure a scheduled task that will force the disconnected sessions to actually be closed.

I’m using the command line tool qwinsta that is shipped with your Windows installation. So you don’t have to install anything to run this script. qwinsta shows you all the RDP sessions with their state, user and id. When you have found the disconnected sessions you can kill them thanks to the command line tool rwinsta.

The script is pretty simple, it just parses the result of the qwinsta command and calls rwinsta for each disconnected session.

To use it, you can call it from the server hosting the sessions or call it from anywhere and use the server parameter to specify the target machine. Note that you have to be joined to the domain of the target machine if you are using it remotely.

I hope this script will help you keep your server clean off disconnected sessions 🙂