Skip to content

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

2011/02/20

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 {
 param($ha)
 "in subroutine" | write-host
 $ha["key1"]  | write-host
 $ha.key1 = 33
 }
$calling=@{}
$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
11

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
$p1 = 33
}
$key2 = 22
$key1 = 11
get-xyz $key1 $key2
"afterwards"
$key1
$key2

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

in subroutine
11
afterwards
11
22
Advertisements

From → arrays, powershell

Leave a Comment

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: