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).
When calling the function, you must use @hashtable1 and not $hashtable1. Using the variable name passes the variable as a HashTable object type instead of passing the keys and values. The @ syntax is a shorthand technique for passing parameters to a function or script.
Object Types in HashTables You can display the hash table in $p and use the key-name properties to display the values. The keys in a hash table can also be any . NET type. The following statement adds a key/value pair to the hash table in the $p variable.
You can pass the parameters in the PowerShell function and to catch those parameters, you need to use the arguments. Generally, when you use variables outside the function, you really don't need to pass the argument because the variable is itself a Public and can be accessible inside the function.
In the first method, the one that I prefer, you can use the GetEnumerator method of the hash table object. In the second method, instead of iterating over the hash table itself, we loop over the Keys of the hash table. Both of these methods produce the same output as our original version.
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With