我有一个包含计算机列表的文件,我需要遍历该列表并报告是否有空闲。Foreach try catch
$list = get-content "pathtofile.txt"
foreach ($computer in $list) {
try {
quser /server:$computer
} catch [System.Management.Automation.RemoteException] {
Write-Host "$computer is free"
}
}
现在,它的工作原理,但我想抓住抓住错误消息,并将其更改为乱七八糟的计算机名称是免费的。
目前它仍然是返回
quser : No User exists for * At line:5 char:5 + quser /server:$computer + ~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (No User exists for *:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError
对于那些免费的电脑。
我能够对我认识的一个计算机运行quser
命令获取System.Management.Automation.RemoteException
是免费的,然后运行$Error[0] | fl * -Force
:
writeErrorStream : True PSMessageDetails : Exception : System.Management.Automation.RemoteException: No User exists for * TargetObject : No User exists for * CategoryInfo : NotSpecified: (No User exists for *:String) [], RemoteException FullyQualifiedErrorId : NativeCommandError ErrorDetails : InvocationInfo : System.Management.Automation.InvocationInfo ScriptStackTrace : at , : line 1 PipelineIterationInfo : {0, 0}
这给了我异常代码。
现在我看看Foreach error handling in Powershell这表明我的代码应该是正确的,所以不知道为什么catch不起作用。
谢谢,伙计,这个代码工作一种享受。 –