Use a PowerShell
script to force logoff an RDP session
When end users remain logged in to an RDP session,
it consumes valuable resources. Use this PowerShell script to force users to
log off.
It's
not a new problem: An end user logs in to a Windows server using Remote Desktop
Protocol and then forgets to log off. When a session remains open, it continues
to consume resources on the server unnecessarily. There's a PowerShell script you can use to
force end users to log off and free up those resources.
To
begin a force logoff of a user'sRemote Desktop Protocol (RDP) session, an admin must
first query all the Remote Desktop Services' (RDS) server sessions on the
machine and check their status. After detecting all disconnected services, the
next step is the force logoff.
Download
the free PowerShell module called PSTerminalServicesand
ensure it's available in your PowerShell. All the installation instructions
are on the PSTerminalServices site.
The
first step I'll take with this module is to see if I can get all of the active
sessions on my lab server -- HYPERV (Figure 1).
Get-TSSession -ComputerName HYPERV
Currently,
I only have a couple sessions in a disconnected state. So, I'm seeing all of
the sessions, but I only want to see those that are disconnected. To do that,
I'll add the State parameter (Figure 2).
Get-TSSession -ComputerName HYPERV -State Disconnected
This
is helpful, but there's still a problem. Session 0 is not an RDP session, and
there’s no way to remove that from the result with Get-TSSession. I'll use
Where-Object to remove that session as well (Figure 3).
Get-TSSession -ComputerName HYPERV -State
Disconnected | where { $_.SessionID -ne 0 }
Now,
I can view all of the sessions I want to stop. Next, I just need to kill these
sessions. To do this, the PSTerminalServices module has a Stop-TSSession
cmdlet. This cmdlet does exactly what you think it does -- it kills the session
(Figure 4).
Get-TSSession -ComputerName HYPERV -State
Disconnected | where {$_.SessionID -ne 0} | Stop-TSSession
The
Stop-TSSession cmdlet forcefully logs off a session, which might cause end
users to lose their work, so it prompts the admin. I could just hit
"A" here and move on, but sometimes admins don't want to be prompted.
If you plan to include this in a larger script, a prompt will break the script.
The best bet is to remove that confirmation.
The
Stop-TSSession cmdlet has a common PowerShell parameter, called –Force, which
allows admins to perform the action without any confirmation.
Get-TSSession
-ComputerName HYPERV -State Disconnected | where {$_.SessionID -ne 0} |
Stop-TSSession -Force
If
you receive no output, the session was logged off successfully.
No comments:
Post a Comment