【发布时间】:2022-01-19 02:58:53
【问题描述】:
我正在使用以下脚本运行指定 Active Directory OU 中的所有服务器并注销指定用户。这在前 35 台服务器上运行得非常好,但在它迭代的最后一台服务器上总是出错。错误是:
Program 'quser.exe' failed to run: Object reference not set to an instance of an object. At line:6 char:24
+ $result = (quser $userAccount)
+ ~~~~~~~~~~~~~~~~~~.
At \\path\to\script.ps1:79 char:5
+ invoke-command -ComputerName $server -ScriptBlock $scriptBlock -A ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (Program 'quser....~~~~~~~~~~~~~~.:String) [], RuntimeException
+ FullyQualifiedErrorId : Program 'quser.exe' failed to run: Object reference not set to an instance of an object.At line:6 char:24
+ $result = (quser $userAccount)
+ ~~~~~~~~~~~~~~~~~~.
我对错误的解读是它认为 $userAccount 没有价值。这是正确的,如果是这样,任何人都可以指出我所缺少的吗?提前谢谢!
Write-Host " "
Write-Host "This script will log out all active sessions for the specified user. Proceed with caution." -ForegroundColor Black -BackgroundColor Yellow
Write-Host " "
$servers = [System.Collections.ArrayList]::new()
foreach ($server in (Get-ADComputer -SearchBase "OU=FictionalDepartment,DC=Company,DC=net" -Filter "OperatingSystem -like 'Windows Server*'" -Properties Name | select -ExpandProperty name))
{
$servers.add($server) | Out-Null
}
$servers.Sort()
$userAccount = Read-Host "Enter account to log out"
Write-Host " "
foreach ($server in $servers)
{
$scriptBlock = {
param($userAccount)
$ErrorActionPreference = 'Stop'
try
{
$result = (quser $userAccount)
$session = ((quser $userAccount)[1] -split "\s+")[2]
logoff $session
Write-Host " The user was logged into session #$session. They have been LOGGED OFF." -ForegroundColor Yellow
}
catch
{
if ($_.Exception.Message -match 'No user exists')
{
Write-Host " User is not logged in." -ForegroundColor Green
}
else
{
throw $_.Exception.Message
}
}
}
Write-Host "$server"
Invoke-Command -ComputerName $server -ScriptBlock $scriptBlock -ArgumentList $userAccount
$session = $null
}
【问题讨论】:
-
如果您从
Invoke-Command中删除-ArgumentList参数并在您的脚本块中删除param(...)块并使用$using:userAccount而不是$userAccount会发生什么?另外,所有$scriptblock变量都应该在循环之外。 -
你能查询那个特定的系统,看看有没有返回吗?
-
@SantiagoSquarzon,使用该方法的效果相同。感谢您的提示——我已将 $scriptBlock 移到 for 循环之外。
-
@AbrahamZinala 如果我运行“quser
/SERVER: ”,我不会收到错误消息。也许我会修改脚本以像那样运行它而不是使用 Invoke-Command。 -
我建议这样做。特别是如果您不能 100% 确定 quser.exe 不在远程系统上。
标签: powershell for-loop invoke-command