PowerShell: How to Logoff an User RDP Session

$servername='servername'
$userName='brucelee'
 
function logOffRdpSession{
    param(
      $serverName=$env:computername,
      $username
    )
    $username=if($username -match '\\'){[regex]::match($username,'\\(.*)$').captures.groups.value[1]
      }else{
        $username.tostring()
      }
    $sessions=qwinsta /server:$serverName
    $sessionId=.{
        $sessionMatch=$sessions|?{$_ -match $username}
        if($sessionMatch){
            $array=$sessionMatch -replace '(^\s+|\s+$)','' -replace '\s+',' ' -split ' '
            return $array|?{$_.tostring() -match '\d+'}
        }else{
            return $null   
        }
    }
    if($sessionId){
      $sessionId|%{rwinsta $_ /SERVER:$serverName}
      $sessions=qwinsta /server:$serverName
      $newSessionId=.{
          $sessionMatch=$sessions|?{$_ -match $username}
          if($sessionMatch){
              $array=$sessionMatch -replace '(^\s+|\s+$)','' -replace '\s+',' ' -split ' '
              return $array[2]
          }else{
              return $null   
          }
      }
      if(!$newSessionId){
        write-host "$username RDP session ID $sessionId on $serverName has been forcefully disconnected."
      }else{
        write-warning "$username RDP session ID $sessionId still exists on $serverName"
      }      
    }else{
      write-host "$username doesn't have an RDP session on $serverName"
    }
}
 
logoffRdpSession $servername $username
Manual Method (less reliable):

Step 1: find the session

quser
USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME
linda-adm 2 Disc 18+20:20 8/8/2019 4:42 PM
johnn 7 Disc 10 8/27/2019 1:56 PM

Step 2: kill the session

Invoke-RDUserLogoff -HostServer localhost -UnifiedSessionID 7 -Force

Leave a Reply

Your email address will not be published. Required fields are marked *