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: Obtaining SQL Database Default Paths

# This function returns an array of 3 string values reflecting default Data, Log, and…

PowerShell: Synchronize Directories with File Signature Comparisons

<# fileCompare_v0.01.ps1- Requires that the source and destination paths are hosted on Windows machines, not…

Manually Create a SSL Certificate with LetsEncrypt

Step 1: Install certbot-auto mkdir /etc/letsencryptcd /etc/letsencrypt/wget chmod a+x certbot-auto Step 2: Create the Cert…