Close disconnected remote sessions using PowerShell

Do you know this situation? You are responsible for some servers and you planned to do some patching during the weekend. You open a remote desktop to the server with the administrator user and you see that the session is still active. Visual Studio is open with unsaved source code, some config files are open, even somebody’s Facebook is nicely ready for you…
Or you start to install some critical updates and when you want to reboot, Windows tells you that there are other users logged on… you check the users tab in the task manager and you see some “disconnected” sessions. Arggh! 👿

I grew tired of reminding people to log off instead of just closing the session. Some people listened, some are too lazy and won’t listen.

So, I wrote myself a little script which runs every evening and terminates all disconnected sessions, regardless of unsaved shizzle that’s happening in them. Really, people only learn to follow the rules when you hit them where it hurts. Sad, but true.

So, here’s the script…

I created a task in the task scheduler to run this every evening at 9PM.

You can find this script in my GitHub PowerShell repository.