在我的脚本中,为了确定是否发生错误,我需要执行两个额外的远程查询。 这些过程大约需要200毫秒,如果用户仍然忽略该错误,那将毫无意义。 有没有一种方法可以确定是否通过-ErrorAction SilentlyContinue调用了我? 还是如果呼叫者不想要验证,是否必须添加一个单独的开关来禁止验证?

===============>>#1 票数: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

  ask by VoidStar translate from so

未解决问题?本站智能推荐: