2013-03-21 73 views
16

我的情況:ErrorActionPreference和ErrorAction SilentlyContinue爲GET-PSSessionConfiguration

$ErrorActionPreference = "Stop"; 
"1 - $ErrorActionPreference;" 
Get-ChildItem NoSuchFile.txt -ErrorAction SilentlyContinue; 
"2 - $ErrorActionPreference;" 
Get-ChildItem NoSuchFile.txt -ErrorAction Stop; 
"3 - $ErrorActionPreference;" 

輸出:

1 - 停止;
2 - 停止;
並顯示錯誤...

現在,

$ErrorActionPreference = "Stop"; 
"1 - $ErrorActionPreference;" 
(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) 
"2 - $ErrorActionPreference;" 

輸出:

1 - 停止;
並顯示錯誤...

爲什麼不爲GET-PSSessionConfiguration工作-ErrorAction SilentlyContinue)?

更新:

現在,

$ErrorActionPreference = "Continue" 
"1 - $ErrorActionPreference;" 
(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) 
"2 - $ErrorActionPreference;" 

輸出:

1 - 繼續;
2 - 繼續;

現在,

$ErrorActionPreference = "SilentlyContinue" 
"1 - $ErrorActionPreference;" 
(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) 
"2 - $ErrorActionPreference;" 

輸出:

1 - SilentlyContinue;
2 - 默默繼續;

reference

ErrorAction無處不參數可用於使用參數值SilentlyContinue沉默非終止錯誤,它可以用於轉換使用參數值Stop非終止錯誤終止錯誤。然而,它無法幫助您忽略終止錯誤,在這種情況下,Stop-Transcript會拋出終止錯誤。如果你想忽略,使用一個try/catch例如爲:

try { Stop-Transcript } catch {} 

回答

18

對我一個解決方案:

$old_ErrorActionPreference = $ErrorActionPreference 
$ErrorActionPreference = 'SilentlyContinue' 
if((Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) -eq $null) { 
    WriteTraceForTrans "The session configuration MyShellUri is already unregistered." 
} 
else {   
    #Unregister-PSSessionConfiguration -Name "MyShellUri" -Force -ErrorAction Ignore 
} 
$ErrorActionPreference = $old_ErrorActionPreference 

或者使用的try-catch

try { 

(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) 

} 
catch { 

} 
+4

我不知道'catch'獲得異常仍需要'-ErrorAction Stop':| – AceMark 2015-01-29 02:58:28

0

看起來這是一個「未處理的異常」,意思本身並沒有被編碼的​​識別和處理該異常的小命令。它發生崩潰而無法運行它的內部錯誤處理,因此cmdlet上的-ErrorAction設置從未發揮作用。

1

Tip #2

不能使用經典2>重定向操作。

(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) 2> $NULL 
if(!$?){ 
    'foo' 
} 

我不喜歡錯誤,所以我不惜一切代價避免它們。

相關問題