如何将哈希表传递给PowerShell中的函数? [英] How do you pass a hash table to a function in PowerShell?
问题描述
将哈希表传递给我的PowerShell函数时,它抱怨说它接收到一个对象.
When passing a hash table to my PowerShell function, it complains that it receives an object.
Function ExtendHash(){
param(
[hashtable] $source,
[hashtable] $extender
)
...
}
呼叫者:
$hash1 = @{One = 1; Two = 2}
$hash2 = @{Two = 22; three = 3}
ExtendHash($hash1, $hash2)
无法将类型为System.Object []的System.Object []值转换为类型为System.Collection.Hashtable
Cannot convert the System.Object[] value of type System.Object[] to type System.Collection.Hashtable
那么我该如何做呢?有建议吗?
So how do I make this work? Suggestions?
我还缺少内置的东西吗?我希望使用与JavaScript用于扩展默认选项(合并和覆盖默认值)相同的模式.
Also, am I missing something built-in? I want the same pattern as what JavaScript uses to extend default options (merge and override default values).
推荐答案
请勿使用括号和逗号.这是PowerShell(例如,参数类似于CMD中命令的参数).也就是说,像这样调用您的函数:
Do not use parenthesis and commas. This is PowerShell (say, arguments are similar to arguments of commands in CMD). That is, call your function like this:
ExtendHash $hash1 $hash2
在您的情况下,表达式($hash1,$hash2)
是一个包含两个项目的数组,并将此数组(一个参数)传递给函数.这样的呼叫正确失败.
In your case expression ($hash1,$hash2)
is an array of two items and you pass this array, one argument, to the function. Such a call fails correctly.
如果使用Set-StrictMode -Version 2
,则PowerShell会捕获此常见"错误:
If you use Set-StrictMode -Version 2
then this "common" mistake is caught by PowerShell:
函数或命令就像是方法一样被调用.参数 应该用空格隔开.有关参数的信息,请参见 about_Parameters帮助主题.
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中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!