当我想在Powershell脚本遇到错误时停止它时,我应该如何停止该脚本?
-ErrorAction -Stop ..
try {
foo.bar
catch{
$ErrorMsg = "An error occured during foo.bar"
Write-Error -Message $ErrorMsg -ErrorAction Stop
}或
try {
foo.bar
catch{
$ErrorMsg = "An error occured during foo.bar"
Write-Error -Message $ErrorMsg
exit
}最好的实践和推荐是什么?
发布于 2020-11-03 20:45:50
您可以预先将$ErrorActionPreference设置为停止,然后在try{}中调用您的脚本。如果脚本遇到错误,它应该使用throw,该错误将终止脚本,使其冒泡到调用脚本。
就像这样
$oldErrorAction = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
try {
foo.bar
}
catch{
# re-throw the exception
throw
}
finally {
# reset the ErrorActionPreference
$ErrorActionPreference = $oldErrorAction
}https://stackoverflow.com/questions/64662275
复制相似问题