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

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


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.


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