gpt4 book ai didi

powershell - 非终止错误处理-if $ Error.count和$ ErrorActionPreference = 'stop'之间的区别

转载 作者:行者123 更新时间:2023-12-03 07:49:27 25 4
gpt4 key购买 nike

我需要处理Powershell脚本中的非终止错误。最有效的方法是什么?

$ErrorActionPreference变量设置为停止并使用try/catch

$ErrorActionPreference = 'stop'
try{
functionThatCanFail
}catch{
#Do Stuff
}

或清除 $Error变量,然后评估是否已填充
$Error.Clear()
functionThatCanFail
if( $Error.Count -ne 0){
#Do Stuff
}

最佳答案

最简单的方法是使用 -ErrorVariable/-ev公用参数,该参数将给定cmdlet报告的所有非终止错误记录在指定变量中。

但是请注意,此仅适用于cmdlet和高级功能/脚本,因为仅它们支持common parameters-有关如何将自己的功能定义为高级功能的信息,请参见Patrick's helpful answer

# Provoke a non-terminating error and silence it, 
# but store it in custom variable $err via common parameter -ErrorVariable
Get-Item /NoSuchFile -ErrorAction SilentlyContinue -ErrorVariable err

if ($err) { # if a / a least one non-terminating error was reported, handle it.
"The following non-terminating error(s) occurred:`n$err"
}

这样, 错误分析是命令范围内的,而不必记录 session 级 $Error集合的状态或更改其状态。

但是请注意,您无法使用这样的方式处理 终止错误。
有关PowerShell错误处理的全面概述,请参见here

关于powershell - 非终止错误处理-if $ Error.count和$ ErrorActionPreference = 'stop'之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46042168/

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