PowerShell:为什么一个参数上的[Parameter(Mandatory = $ True)]影响另一个参数的类型转换行为?

Gia*_*lon 3 arrays string powershell casting

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

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

执行此代码块时,将产生错误:test:无法处理参数'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
Run Code Online (Sandbox Code Playgroud)

预先感谢您的反馈

box*_*dog 5

通过添加[Parameter()]属性,您就隐含了该[CmdletBinding()]属性(即,将该功能转换为Advanced Function)。如果在使用时查看行为的源代码[CmdletBinding()],您会发现它明确禁止将数组转换为字符串,这就是您要尝试的操作。

要了解它特定于数组,请尝试例如$b = Get-Date(即传递一个DateTime对象)。转换为字符串可以正常工作。