2017-04-10 64 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 
    } 
} 

}