01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# logOffUser.ps1
 
$servername=$env:computername
$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 logged off."
      }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