gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:50:23 24 4
gpt4 key购买 nike

在我的脚本中,为了确定是否发生错误,我需要执行两个额外的远程查询。这些过程大约需要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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com