Blog Archive

Thursday, August 3, 2017

Combine arrays with hash tables in PowerShell

Very often when I'm scripting something more complex in PowerShell, I found very powerful to combine arrays with hash tables.
I like hash tables because of the relationship between key and their values, but what if you need to have more values bound to one key? No problem! Insert your array directly to hash table. Lets see how:


1) Declare your empty hash table:
$Hash = @{}


2) Prepare your array variables:
$Group1 = "a", "b", "c"


$Group2 = "d", "e", "f"


3) Add array variables directly to hash table:
$Hash.Add("Group1", $Group1)


$Hash.Add("Group2", $Group2)


Of course my recommendation is to at first check if key does not exists in hash and only then add it, or if it already exists, you need to set existing key-value pair inside hash table. You can use this approach:
If($Hash.ContainsKey($key))
{
 $Hash.Set_Item($Key, $Value)
}
Else
{
  $Hash.Add($Key, $Value)
}


4) See the result:
$Hash

You should see this output:


Now you can use your array values in any way you need:
$Values = $Hash.Get_Item("Group1")
$Value1 = $Values[0]
$Value2 = $Values[1]
$Value3 = $Values[2]


Hope this short tutorial was helpful at least for me when I will need combine arrays with hash next time :)

1 comment: