1
在我的腳本中,爲了確定是否發生錯誤,我需要做兩個額外的遠程查詢。這些需要大約200毫秒,並且如果用戶忽略錯誤則毫無意義。有沒有辦法確定我是否用-ErrorAction SilentlyContinue
撥打電話?或者如果調用者不需要,還是必須添加一個單獨的開關來抑制驗證?在Powershell中,我可以確定我的函數是否使用-ErrorAction SilentlyContinue調用?
在我的腳本中,爲了確定是否發生錯誤,我需要做兩個額外的遠程查詢。這些需要大約200毫秒,並且如果用戶忽略錯誤則毫無意義。有沒有辦法確定我是否用-ErrorAction SilentlyContinue
撥打電話?或者如果調用者不需要,還是必須添加一個單獨的開關來抑制驗證?在Powershell中,我可以確定我的函數是否使用-ErrorAction SilentlyContinue調用?
如果需要,可以檢查$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
我剛剛做了一個實驗,'$ ErrorActionPreference'似乎完全不受'-ErrorAction'的影響。我需要檢測'-ErrorAction SilentlyContinue'。 – VoidStar
@VoidStar'$ ErrorActionPreference'變量受到'-ErrorAction'影響,至少在運行Win8.1 Update 1和PowerShell 4的計算機上。我已經添加了一個測試此行爲的示例。 –
我沒有意識到-ErrorAction只在函數有[CmdletBinding()]時做了些什麼。 – VoidStar