Remotely Logging off RDP Sessions

In our lab, we don't have Terminal Services Licensing set up.  This means our servers have only 2 logon sessions per host.  We have a GPO in place to log off non-console sessions after 24 hours of idle time, but we also have tradition of playfully chiding people idling on the logon sessions.

Here's a script to log off a bunch of machines:

 function Logoff-RemoteComputer {
    param (
        [string[]]$computer = @(),
        [string]$userName = $env:USERNAME,
    if ($verbose) { $local:verbosePreference = 'continue'; }
    $quser = (Get-Command -CommandType Application -Name quser -ErrorAction SilentlyContinue).Definition
    if (!$quser) {
        Write-Warning "qusuer.exe not found. Skipping.";
        return $false;
    } else {
        Write-Verbose "quser found at $quser";
        foreach ($myComputer in $computer) {
            if (!$myComputer) { continue;}
            Write-Progress "querying" $myComputer;
            Write-Verbose "processing $myComputer";
            foreach ($mySession in (& cmd /c $quser /server:$myComputer "2>NUL" | Select-String $userName)) {
                Write-Verbose "Session: $mySession";
                if ($mySession -match $userName) {
                    $sessionName = $mySession -replace "^\s*$userName\s+" -replace "\s+.*";
                    Write-Progress "logging off" $mySession;
                    Write-Verbose "session $Sessionname";
                    logoff $sessionName /server:$myComputer;


Comments (1)

  1. timdunn says:

    On a related note, if we search for "s0s" instead of "$userName", we can get all the people sitting on the /console (or /admin) session.

Skip to main content