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

标签 powershell error-handling

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

最佳答案

您可以根据需要检查$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

关于powershell - 在Powershell中,我可以确定是否通过-ErrorAction SilentlyContinue调用了我的函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23190700/

相关文章:

powershell - 对Foreach对象的错误处理

c++ - 我正在尝试制作一个循环来检查输入是否为数字,如果不是则再次询问

Powershell PromptForChoice - 如何编辑描述?

windows - 如何使用 Windows 命令行下载文件而无需输入代理密码?

powershell - 如何在Powershell中将用户添加到本地管理员组?

python - 整理一系列的 try... except 语句?

python - 无论如何,在退出时关闭sqlite3数据库

arrays - Powershell逐字读取文本文件

powershell - 运行旧版本的 Windows PowerShell ISE

web-applications - 进入生产环境后处理 Web 应用程序中的错误的方法