我们正在大容量地检索所有已安装的打印机。为此,我们在Get-Printer CmdLet上使用了Get-Printer开关。当所有ComputerNames都存在时,这很好,但是当存在一个不存在的错误时,就会正确地抛出错误。
示例
$ComputerName = @('Computer1', 'NonExisting', 'Computer2')
$GetPrinterJobs = Foreach ($C in $ComputerName) {
Get-Printer -ComputerName $C -AsJob
}
$GetPrinterJobs | Wait-Job -EA Ignore | Receive-Job此代码将为NonExisting ComputerName抛出一个错误。如何才能看到错误实际上来自ComputerName NonExisting?
获取-打印机:无法访问假脱机程序服务.确保假脱机程序服务正在运行。
在下面@JosefZ的帮助下,解决了,如下所示:
$GetPrinterJobs = Foreach ($C in $ComputerName) {
$C
Get-Printer -ComputerName $C -AsJob
}
$null = Get-Job | Wait-Job -EA Ignore
$GetPrinterJobResults = for ( $i = 0; $i -lt $GetPrinterJobs.Count; $i += 2 ) {
$ReceiveParams = @{
ErrorVariable = 'JobError'
ErrorAction = 'SilentlyContinue'
}
$ReceivedJobResult = $GetPrinterJobs[$i + 1] | Receive-Job @ReceiveParams
[PSCustomObject]@{
ComputerName = $GetPrinterJobs[$i]
State = $GetPrinterJobs[$i + 1].State
Data = $ReceivedJobResult
Error = if ($JobError) {
$JobError
$JobError.ForEach( { $Error.Remove($_) })
}
}
}
$GetPrinterJobResults发布于 2019-07-11 14:44:27
这是我的老办法:
$ComputerName = @('Computer1', 'NonExisting', 'Computer2')
$GetPrinterJobs = Foreach ($C in $ComputerName) {
$C
Get-Printer -ComputerName $C -AsJob
}
$GetPrinterJobResults = $GetPrinterJobs |
Where-Object { $_.GetType().Name -ne 'String'} |
Wait-Job -EA Ignore | Receive-Job
for ( $i = 0; $i -lt $GetPrinterJobs.Count; $i+=2 ) {
@{
$GetPrinterJobs[$i] = $GetPrinterJobs[$i + 1].State
}
}应该返回类似的东西
Name Value
---- -----
Computer1 Completed
NonExisting Failed
Computer2 Completed https://stackoverflow.com/questions/56990080
复制相似问题