Disconnect inactive RDP sessions

Many admins know the problem: they don’t have terminal servers for administration, so there are 2 RDP sessions to a server possible. And when connecting to  a server there are either no free sessions or many disconnected (not “logged-off”) sessions which are cosuming resources which is slowing down the server.

If you only want to see the sessions, you can execute only this:

query user | select -Skip 1 | ? {($_ -split "\s+")[-4] -eq 'Disc'} 

 

To disconnect all these sessions at once, you can execute this command inside an elevated PowerShell window:

query user | select -Skip 1 | ? {($_ -split "\s+")[-4] -eq 'Disc'} | % {logoff ($_ -split "\s+")[-5] /v}

 

 

And then all disconnected RDP sessions are forced logoff and the resources are free.

 

Published by Andreas

Founder of M365 Evangelists Cloud-Architect, Strategy Consultant, Consultant for Microsoft technologies, Graph API enthusiast, PowerShell enthusiast