How do you pass a hash table to a function in PowerShell?

只愿长相守 提交于 2020-01-24 02:02:33

问题


When passing a hash table to my PowerShell function, it complains that it receives an object.

Function ExtendHash(){
  param(
    [hashtable] $source,
    [hashtable] $extender
  )
  ...
}

And the caller:

$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

So how do I make this work? Suggestions?

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).


回答1:


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

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.


If you use Set-StrictMode -Version 2 then this "common" mistake is caught by 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.




回答2:


(next to Roman's answer:)
The caller does not need to store the hashtables in variables and one can then also use this:

ExtendHash  -source @{One = 1; Two = 2}  -extender @{Two = 22; three = 3}

(-source and -extender are necessary so the hashtables themselves do not get interpreted as arg-value-pairs by itself for ExtendHash)



来源:https://stackoverflow.com/questions/12931043/how-do-you-pass-a-hash-table-to-a-function-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!