有人知道为什么参数 $a 上的 Mandatory 属性会影响参数 $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
提前感谢您的反馈
最佳答案
通过添加 [Parameter()]
属性,您暗示了 [CmdletBinding()]
属性(即将函数转换为 Advanced Function )。如果你look at the source code对于使用 [CmdletBinding()]
时的行为,您会看到它明确禁止将数组转换为字符串,而这正是您想要做的。
要查看它是否特定于数组,请尝试,例如,$b = Get-Date
(即传递一个 DateTime
对象)。到字符串的转换工作正常。
关于arrays - PowerShell:为什么一个参数上的 [Parameter(Mandatory = $True)] 会影响另一个参数的类型转换行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58272608/