Disconnected RDP sessions are one of those small problems that quietly cost a Windows team time. Someone closes the Remote Desktop window instead of signing out, the session sits in Disc state for days, and eventually it holds a licence, keeps a profile locked, blocks a reboot or eats memory on a busy server.
Logging in to each server to check Task Manager → Users doesn’t scale past a handful of machines. This post shows how I approach it with plain PowerShell: list sessions across many servers, pick out the stale disconnected ones, and log them off – with a report-only mode first.
Examples use made-up server names. Test in a non-production environment and follow your own change process before logging anyone off.
What we want
- One command that lists every user session on a list of servers
- Each session as a proper object: server, user, ID, state, idle time
- A filter for disconnected sessions idle longer than a threshold (say 4 hours)
- Report-only by default; log off only when explicitly asked
Step 1: read sessions with quser
Windows already ships quser (the same as query user). It works remotely with /server: and needs no extra modules:
quser /server:APP-SRV-01
USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME
alice rdp-tcp#12 2 Active . 11/28/2026 9:02 AM
bob 3 Disc 1+04:10 11/27/2026 6:15 PM
Two things to notice: a disconnected session has no SESSIONNAME, and the idle time can look like ., 45, 2:10 or 1+04:10 (days + hours:minutes). We need to handle both.
Step 2: turn the text into objects
function ConvertTo-IdleMinutes {
param([string]$Idle)
if ([string]::IsNullOrWhiteSpace($Idle) -or $Idle -in @('.', 'none')) { return 0 }
$days = 0
if ($Idle -match '^(\d+)\+(.+)$') { $days = [int]$Matches[1]; $Idle = $Matches[2] }
if ($Idle -match '^(\d+):(\d+)$') { return ($days * 1440) + ([int]$Matches[1] * 60) + [int]$Matches[2] }
return ($days * 1440) + [int]$Idle
}
function Get-RdpSession {
[CmdletBinding()]
param([string[]]$ComputerName = $env:COMPUTERNAME)
foreach ($computer in $ComputerName) {
$lines = quser /server:$computer 2>$null
if (-not $lines) { Write-Verbose "No sessions or no access: $computer"; continue }
foreach ($line in ($lines | Select-Object -Skip 1)) {
$parts = ($line.Trim() -replace '^>', '') -split '\s{2,}'
# Disconnected sessions have no SESSIONNAME, so one column fewer
$hasSessionName = $parts.Count -ge 6
$offset = if ($hasSessionName) { 1 } else { 0 }
[pscustomobject]@{
ComputerName = $computer
UserName = $parts[0]
SessionName = if ($hasSessionName) { $parts[1] } else { $null }
Id = [int]$parts[1 + $offset]
State = $parts[2 + $offset]
IdleMinutes = ConvertTo-IdleMinutes $parts[3 + $offset]
LogonTime = $parts[4 + $offset]
}
}
}
}
Now you can work with sessions like any other PowerShell data:
$servers = Get-Content .\servers.txt
Get-RdpSession -ComputerName $servers | Format-Table -AutoSize
Step 3: report first, then log off
Wrap the clean-up in a function that supports -WhatIf, so the default run only reports:
function Remove-StaleRdpSession {
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
param(
[Parameter(Mandatory)][string[]]$ComputerName,
[int]$IdleThresholdMinutes = 240
)
$stale = Get-RdpSession -ComputerName $ComputerName |
Where-Object { $_.State -eq 'Disc' -and $_.IdleMinutes -ge $IdleThresholdMinutes }
foreach ($s in $stale) {
$target = "$($s.UserName) (ID $($s.Id)) on $($s.ComputerName), idle $($s.IdleMinutes) min"
if ($PSCmdlet.ShouldProcess($target, 'Log off')) {
logoff $s.Id /server:$($s.ComputerName)
}
}
$stale
}
# Report only
Remove-StaleRdpSession -ComputerName $servers -WhatIf
# Actually log off (asks for confirmation)
Remove-StaleRdpSession -ComputerName $servers
ConfirmImpact = 'High' means PowerShell asks before each log-off unless you pass -Confirm:$false – useful when running interactively.
Step 4: run it from Jenkins
Once it works by hand, a small Jenkins job removes the need to log in at all:
- Parameters: server list (text or file), idle threshold, and a
Modechoice ofReport/LogOff(defaultReport) - Build step: a PowerShell step that loads the functions and calls
Remove-StaleRdpSessionwith-WhatIfwhenMode = Report, or-Confirm:$falsewhenMode = LogOff - Output: export the results with
Export-Csvand archive the CSV as a build artifact, so every run leaves an audit trail - Access: run it with a service account that has rights to query and log off sessions on the target servers
A scheduled nightly run in report mode, plus an on-demand log-off run, covers most teams’ needs.
Gotchas
- Localised Windows:
quseroutput is translated on non-English servers (for example the state is notDisc). Check the state value on your servers or filter on the missing session name instead. - Long user names can shrink the spacing between columns. If parsing looks off, print the raw
quserline for that server. - Access denied / RPC errors: remote
quserneeds RPC access to the server and the right permissions. The function skips servers it can’t read and tells you with-Verbose. - Unsaved work: a disconnected user may still have files open. That’s why report mode and a sensible idle threshold come first.
FAQ
How do I log off a disconnected RDP session from the command line?
Run quser /server:SRV01 to see the session ID, then logoff <ID> /server:SRV01. The function above does the same across many servers.
Does a disconnected RDP session use server resources? Yes. The user’s apps keep running, so memory, CPU, open files and the Remote Desktop licence stay in use until the session is logged off.
Can Windows log off disconnected sessions automatically? Yes – the Group Policy setting Set time limit for disconnected sessions (under Remote Desktop Session Host → Session Time Limits) ends them after a set time. The script is useful when you need a report first or the policy isn’t in place.
Watch it in 30 seconds
The short video version is on WinOps Academy on YouTube.
Wrap-up
A few dozen lines of PowerShell turn a manual, log-in-and-check chore into a repeatable job with a report, a dry run and an audit trail. In a coming guide I’ll cover rolling out a portable OpenSSH upgrade to Windows servers the same way.
If you run something similar, I’d like to hear how you handle it – connect with me on LinkedIn.
Practise this topic
Test yourself with free questions on this topic – instant answers and explanations.
Start practice questionsPowerShellWindows ServerRDPRemote DesktopAutomationJenkinsSRESysAdmin