首页 > 解决方案 > 远程注销用户

问题描述

发现此脚本注销单个用户名

$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

是否可以对所有登录会话的用户执行相同的操作?

我知道 -match 返回第一个参数,我尝试执行“-ne $Null”,但它返回一整列会话而不是一行,并且只检查行 [0] 和具有实际参数的行...

标签: powershellremote-accesslogoff

解决方案


遍历集合并注销所有存在的 Id:

$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

推荐阅读