gpt4 book ai didi

PowerShell函数参数验证

转载 作者:行者123 更新时间:2023-12-03 00:42:06 26 4
gpt4 key购买 nike

假设我有一个函数附加值,当参数给出一个字符串而不是整数时,如何避免出现丑陋的错误消息?

Function Add-Values
{
param(
[parameter(mandatory=$true)][int]$val1,
[parameter(mandatory=$true)][int]$val2
)

$val1 + $val2
}

感谢您的帮助

最佳答案

Janne Tuukkanen's helpful answer提供了有效的解决方案。

退一步:

想要避免 Windows PowerShell 和 PowerShell [Core] 6.x 中臭名昭著的多行默认错误格式,这是可以理解的> 版本,这可能会让最终用户感到困惑。

两个次优选项是:

  • 使用$host.UI.WriteErrorLine($errMsg) ,它只打印 $errMsg 的内容红色,没有任何附加信息。

  • 另一个选项是使用 Write-Warning $errMsg ,它以黄色打印消息,但在其前面加上 WARNING: 前缀。 .

不过,一般来说,最好不要绕过常用的错误报告功能(为了一致性并支持进一步的编程处理),PowerShell [Core] 7 + 可以帮助:

PowerShell [Core] 7+ 现在默认为简洁错误格式,通过 ConciseView 7.0 中引入的 View :

带有偏好变量 $ErrorView设置为新的默认值 ConciseView ,如果给定非整数,您的命令将失败,如下所示(以红色打印在单行上;为了便于阅读,在此处跨多行打印):

Add-Values: Cannot process argument transformation on parameter 'val1'. 
Cannot convert value "abc" to type "System.Int32".
Error: "Input string was not in a correct format."

屏幕截图(自定义背景颜色):

enter image description here

虽然相对于旧格式确实有所改进,但它仍然有些冗长。

但是,您可以通过 [ValidateScript()] 对参数执行自定义验证属性,在 PowerShell v6+ 中还支持 ErrorMessage属性,因此您可以执行以下操作:

Function Add-Values
{
param(
[ValidateScript({ ($_ -as [int]) -is [int] }, ErrorMessage='Please pass an integer.')]
[Parameter(Mandatory)]
$val1
,
[ValidateScript({ ($_ -as [int]) -is [int] }, ErrorMessage='Please pass an integer.')]
[Parameter(Mandatory)]
$val2
)

$val1 + $val2
}

注意:

  • [ValidateScript()]属性接受一个脚本 block ,其中用户传递的值反射(reflect)在自动 $_ 中。多变的。脚本 block 必须输出一个 bool 值,指示该值是否有效 - (有效)$true ) - 或不 - (有效)$false .

  • { ... } 内仅支持脚本 block 文字 ( [ValidateScript()] ) 和(不可扩展的)字符串文字,因此两个参数的值必须重复。

  • ($_ -as [int]) -is [int]使用 -as运算符查看给定参数值 ( $_ ) 是否已经是 [int]或者 可以转换为 1,并返回 [int]实例如果是这样,并且 $null否则。 -is [int]然后测试 -as 是否操作确实返回了一个整数或没有返回一个整数。

使用无效参数 - 例如 Add-Values abc 2 - 然后你会得到类似下面的内容:

enter image description here

关于PowerShell函数参数验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59104970/

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