Skip to content

Add name – value pairs to hash arrays and pass multi values to a function with less typing


What I didn’t realize before that you don’t need to use the add method to add elements to an hasharray.

$myHashArry = @{}
$myHashArry.Add("myKey1", "valueA")
$myHashArry.Add("myKey2", "valueB")

you can also use

$myHashArry = @{}
$myHashArry.myKey1 = "valueA"
$myHashArry.myKey2 = "valueB"

This seems to be useful at least during testing to pass a bunch of parameters to a function without also updating the param () block of the function definition. The other characteristic that can be useful is that a complex type like the hasharray is passed by reference. That means that changes to that variables are seen in the calling function:

function get-xyz {
 "in subroutine" | write-host
 $ha["key1"]  | write-host
 $ha.key1 = 33
$calling.key2 = 22
$calling.key1 = 11
$calling | ft
get-xyz $calling
$calling  | ft

Output: the variable in the calling scope was changed:

Name                           Value
----                           -----
key2                           22
key1                           11 

in subroutine

Name                           Value 
----                           -----
key2                           22 
key1                           33

When the parameters are passed one by one as a “simple type” they are passed by value the changes in the subroutine are local to the function

function get-xyz {
param($p1 , $p2)
"in subroutine" | write-host
$p1 = 33
$key2 = 22
$key1 = 11
get-xyz $key1 $key2

Output shows that $key1 is still 11 after return from the sub

in subroutine

From → arrays, powershell

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: