Log off users remotely

3k views Asked by At

found this script to log off a single username

$scriptBlock = {
     $ErrorActionPreference = 'Stop'

      try {
         ## Find all sessions matching the specified username
         $sessions = quser | Where-Object {$_ -match 'username'}
         ## Parse the session IDs from the output
         #foreach($sessionsUser in $sessions){
         $sessionIds = ($sessions -split ' +')[2]
         Write-Host "Found $(@($sessionIds).Count) user login(s) on computer."
         ## Loop through each session ID and pass each to the logoff command
         $sessionIds | ForEach-Object {
             Write-Host "Logging off session id [$($_)]..."
             logoff $_
         }
         #}
     } catch {
         if ($_.Exception.Message -match 'No user exists') {
             Write-Host "The user is not logged in."
         } else {
             throw $_.Exception.Message
         }
     }
 }

 ## Run the scriptblock's code on the remote computer
Invoke-Command -ComputerName NAME -ScriptBlock $scriptBlock

Is it possible to do the same for all users logged in session ?

I know that -match return first parameter , i tried to do " -ne $Null" but it returns a whole column with sessions instead a row and only check row [0] and the ones with actuall parameters ...

2

There are 2 answers

3
Scepticalist On BEST ANSWER

Iterate through the collection and logoff all the Id present:

$ScriptBlock = {
    $Sessions = quser /server:$Computer 2>&1 | Select-Object -Skip 1 | ForEach-Object {
        $CurrentLine = $_.Trim() -Replace '\s+',' ' -Split '\s'
        # If session is disconnected different fields will be selected
        If ($CurrentLine[2] -eq 'Disc') {
            [pscustomobject]@{
                UserName = $CurrentLine[0];
                Id = $CurrentLine[1]
            }
        }
        Else {
            [pscustomobject]@{
                UserName = $CurrentLine[0];
                Id = $CurrentLine[2]
            }
        }
    }
    $Sessions | ForEach-Object {
        logoff $_.Id
    }
}


Invoke-Command -ComputerName gmwin10test -ScriptBlock $ScriptBlock
4
hcm On

Instead of

$sessions = quser | Where-Object {$_ -match 'username'}
## Parse the session IDs from the output
#foreach($sessionsUser in $sessions){
$sessionIds = ($sessions -split ' +')[2]

use:

$sessionIDs = @()
$sessions = (quser) -split '`r`n'
for ($i=1;$i -lt $sessions.length;$i++){
    $sessionIDs += $sessions[$i].substring(42,4).trim()
}

This way all sessions are recorded and the IDs are added to the $sessionIDs-array. I'm using substring since the regex is not working if the session is disconnected. Also using forinstead of foreach since the first entry is the header ("ID").