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: Installing or Including an Application On a Computer or Scripting Session

Sample Usage: PS C:\WINDOWS\system32> includeapp -appName notepadplusplus -appExe notepad++notepadplusplus version 7.91.0.0 already exists.True function includeApp($appName,$appExe=$False,$version){…

Manual Sync for Office 365 Azure-AD Integration

1. Perform Prerequisites:* a. Install Dot Net Framework 4.5 )* b. Install Windows Management Framework…

How To Remove A Program on Windows Using PowerShell

# removeAppwizProgram.ps1 # Version 0.02 $computernames=@( 'SERVER0001', 'SERVER0002' ) $appName='Dell EMC OpenManage Systems Management Software…