远程注销用户

时间:2019-12-18 14:44:30

标签: powershell remote-access logoff

找到此脚本以注销单个用户名

$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]和具有实际参数的列... < / p>

2 个答案:

答案 0 :(得分:1)

遍历收集并注销所有存在的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

答案 1 :(得分:0)

代替

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

使用:

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

这样,将记录所有会话,并将ID添加到$sessionIDs数组中。 我正在使用substring,因为如果会话断开连接,则正则表达式无法正常工作。由于第一个条目是标题(“ ID”),因此也使用for而不是foreach

相关问题