首页 > 解决方案 > PowerShell:为什么一个参数上的 [Parameter(Mandatory = $True)] 会影响另一个参数的类型转换行为?

问题描述

有人知道为什么参数 $a 上的强制属性会影响参数 $b 的类型转换行为吗?在示例中,数组应转换为字符串。

function test ([Parameter(Mandatory = $True)] [string] $a, [string] $b) {
  $a; $b
}
$b = "a", "b", "c"
test -a "my string" -b $b

执行此代码块时,会产生错误:测试:无法处理参数“b”上的参数转换。无法将值转换为 System.String 类型。在行:1 字符:31

如果我从 $a 中删除 Mandatory 属性,它可以正常工作:

function test ([string] $a, [string] $b) {
  $a; $b
}
$b = "a", "b", "c"
test -a "my string" -b $b

提前感谢您的反馈

标签: arraysstringpowershellcasting

解决方案


By adding the [Parameter()] attribute, you are implying the [CmdletBinding()] attribute (i.e. turning the function into an Advanced Function). If you look at the source code for the behaviour when using [CmdletBinding()], you'll see that it explicitly disallows conversion of an array to a string, which is what you're trying to do.

To see that it is specific to arrays, try, for example, $b = Get-Date (i.e. pass a DateTime object). The conversion to string works fine.


推荐阅读