将哈希表传递给我的 PowerShell 函数时,它提示它收到了一个对象。
Function ExtendHash(){
param(
[hashtable] $source,
[hashtable] $extender
)
...
}
和来电者:
$hash1 = @{One = 1; Two = 2}
$hash2 = @{Two = 22; three = 3}
ExtendHash($hash1, $hash2)
Cannot convert the System.Object[] value of type System.Object[] to type System.Collection.Hashtable
那么我该如何进行这项工作呢?建议?
另外,我是否缺少内置的东西?我想要与 JavaScript 用于扩展默认选项(合并和覆盖默认值)的相同模式。
最佳答案
不要使用括号和逗号。这是 PowerShell(例如,参数类似于 CMD 中命令的参数)。也就是说,像这样调用你的函数:
ExtendHash $hash1 $hash2
在您的情况下,表达式
($hash1,$hash2)
是一个包含两项的数组,您将此数组(一个参数)传递给函数。这样的调用正确地失败了。如果您使用
Set-StrictMode -Version 2
然后这个“常见”错误被 PowerShell 捕获:The function or command was called as if it were a method. Parameters should be separated by spaces. For information about parameters, see the about_Parameters Help topic.
关于powershell - 如何将哈希表传递给 PowerShell 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12931043/