Posted On August 29, 2019

PowerShell: How to Logoff an User RDP Session

kimconnect 0 comments
blog.KimConnect.com >> Codes >> PowerShell: How to Logoff an User RDP Session
# 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

Leave a Reply

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

Related Post

PowerShell: Unlimit RDP Sessions

$tsRegHive='REGISTRY::HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server' Set-ItemProperty -Path $tsRegHive -Name fSingleSessionPerUser -value 0 Set-ItemProperty -Path $tsRegHive -Name fdenyTSConnections -value…

Another Logon Script Example from 2008

Method 1 - Mixed Environment:1. Edit the following script as appropriate2. Then, save such script…

PowerShell: WinHTTP Proxy

The most direct method to set WinHTTP proxy settings on a Windows machine is to…