在Powershell中,我可以确定是否使用-ErrorAction SilentlyContinue调用了我的函数吗?

时间:2014-04-21 04:13:14

标签: powershell error-handling

在我的脚本中,为了确定是否发生了错误,我需要做两个额外的远程查询。如果用户无论如何都忽略了错误,这些花费大约200毫秒并且毫无意义。有没有办法确定我是否使用-ErrorAction SilentlyContinue进行了调用?或者,如果调用者不想要它,我是否必须添加一个单独的开关来禁止验证?

1 个答案:

答案 0 :(得分:2)

如果您愿意,可以检查$ErrorActionPreference变量以查看应如何处理错误。

如果您执行Get-Help about_preference_variables,则可以阅读有关此变量和其他偏好变量的更多信息。

编辑2014-04-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