PowerShell Param()语句+错误陷阱 [英] PowerShell Param() statement + error trap
问题描述
我们使用以下语句使TeamCity能够识别PowerShell部署脚本中的错误:
We're using the following statement to enable TeamCity to recognize errors in our PowerShell deployment scripts:
trap { $host.SetShouldExit(1) }
这很好用,但是,因为Param(...)必须是第一个语句,所以我们必须使用以下顺序:
This works fine, however, since Param(...) needs to be the very first statement we have to use this order:
Param(
...
)
Set-StrictMode -Version 2.0
$ErrorActionPreference = "Stop"
trap { $host.SetShouldExit(1) }
在Param()评估期间,是否还可以捕获错误?例如.如果我们省略了必填参数,TeamCity目前将无法检测到.
Is there any way to also trap errors during the Param() evaluation? E.g. if we omit a mandatory parameter, TeamCity is not able to detect this at the moment.
推荐答案
这是对Powershell的又一个烦人的疏忽.我发现解决此Powershell错误的最佳方法是推出您自己的强制性验证.它是更多的代码,但清晰,简单且具有故障保护功能.
This is yet another annoying oversight of Powershell. I find the best way to workaround this Powershell bug is to roll your own mandatory verification. It's more code, but clear, simple and fail-safe.
首先从参数声明中删除强制性标志,并在脚本开头检查是否为空.
First remove the mandatory flag from the param declaration and check for null or empty at the beginning of the script.
param (
[string] $required_param
)
# Check required params
if ([string]::IsNullOrEmpty($required_param)) {
Write-Host "The required_param is required."
exit 1;
}
此外,您可以使用常规File参数调用脚本:
Plus you can call your script with the regular File argument:
powershell -File foo.ps1
希望这会有所帮助.
这篇关于PowerShell Param()语句+错误陷阱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!