2017-04-10 66 views
2

我有一个包含计算机列表的文件,我需要遍历该列表并报告是否有空闲。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不起作用。

回答

3
try { 
    $savePreference = $ErrorActionPreference 
    $ErrorActionPreference = 'Stop' 
    quser /server:$computer 2>&1 
} 

catch [System.Management.Automation.RemoteException] { 
    Write-Host "$computer is free" 
} 

finally 
{ 
    $ErrorActionPreference = $savePreference 
} 
+0

谢谢,伙计,这个代码工作一种享受。 –

2

我经常这样做:

$list = get-content "pathtofile.txt" 

foreach ($computer in $list) 
{ 
    try 
{ 
    quser /server:$computer 
} 
catch 
{ 
    if ($Error.Exception -eq "System.Management.Automation.RemoteException: No User exists for *") 
    { 
     Write-Host "$computer is free" 
    } 
    else 
    { 
     throw $error 
    } 
} 

}