2014-04-21 31 views

回答

2

如果需要,可以檢查$ErrorActionPreference變量以查看應該如何處理錯誤。

如果你做Get-Help about_preference_variables,你可以閱讀更多關於這個和其他偏好變量。

編輯2014年4月22日:添加測試這種行爲

一個例子下面是如何測試這樣一個例子:

function Test-Error 
{ 
    [CmdletBinding()] 
    PARAM() 

    Write-Host "Error action preference is '$ErrorActionPreference'" 
    Write-Error "This is a test error" 
} 

Test-Error 
Test-Error -ErrorAction SilentlyContinue 
Test-Error -ErrorAction Continue 
Test-Error -ErrorAction Stop 
Write-Host "We shouldn't get here, since last error action was 'Stop'" 

我們得到以下的輸出:

Error action preference is 'Continue' 
Test-Error : This is a test error 
At line:12 char:5 
+  Test-Error 
+  ~~~~~~~~~~ 
    + CategoryInfo   : NotSpecified: (:) [Write-Error], WriteErrorException 
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Test-Error 

Error action preference is 'SilentlyContinue' 
Error action preference is 'Continue' 
Test-Error : This is a test error 
At line:14 char:5 
+  Test-Error -ErrorAction Continue 
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : NotSpecified: (:) [Write-Error], WriteErrorException 
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Test-Error 

Error action preference is 'Stop' 
Test-Error : This is a test error 
At line:15 char:5 
+  Test-Error -ErrorAction Stop 
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : NotSpecified: (:) [Write-Error], WriteErrorException 
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Test-Error 
+0

我剛剛做了一個實驗,'$ ErrorActionPreference'似乎完全不受'-ErrorAction'的影響。我需要檢測'-ErrorAction SilentlyContinue'。 – VoidStar

+0

@VoidStar'$ ErrorActionPreference'變量受到'-ErrorAction'影響,至少在運行Win8.1 Update 1和PowerShell 4的計算機上。我已經添加了一個測試此行爲的示例。 –

+0

我沒有意識到-ErrorAction只在函數有[CmdletBinding()]時做了些什麼。 – VoidStar

相關問題