Search code examples
powershellremote-accesslogoff

Log off users remotely


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 ...


Solution

  • 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