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

标签 arrays string powershell casting

有人知道为什么参数 $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/

相关文章:

javascript - 在 lodash 中,为什么谓词和结果变量没有以 var 关键字作为前缀?

javascript - 如何根据字符串数组求和的对应值返回字符串

arrays - Powershell解析帮助-中级排序

string - Powershell子串切割

c - 二维数组指针

c++ - 传递给函数的动态数组

c++ - ifstream - 移动到下一个单词

c++ - 使用字符串作为条件时减少 else if 语句的方法

php - 将目录中的所有文件合并/合并到一个文本文件中

powershell - 捕获 Get-EventLog 错误