10. HashTables

Note

The below information is extensively based in information taken from the PowerShell® Notes for Professionals book. I plan to extend this information based on my day to day usage of the language.

A Hash Table is a structure which maps keys to values. See Hash Table for details.

10.1: Access a hash table value by key

An example of defining a hash table and accessing a value by the key

1
2
3
4
5
6
7
$hashTable = @{
  Key1 = 'Value1'
  Key2 = 'Value2'
}
$hashTable.Key1
#output
Value1

An example of accessing a key with invalid characters for a property name:

1
2
3
4
5
6
7
$hashTable = @{
  'Key 1' = 'Value3'
  Key2 = 'Value4'
}
$hashTable.'Key 1'
#Output
Value3

10.2: Creating a Hash Table

Example of creating an empty HashTable:

1
$hashTable = @{}

Example of creating a HashTable with data:

1
2
3
4
5
$hashTable = @{
  Name1 = 'Value'
  Name2 = 'Value'
  Name3 = 'Value3'
}

10.3: Add a key value pair to an existing hash table

An example, to add a "Key2" key with a value of "Value2" to the hash table, using the addition operator:

1
2
3
4
5
$hashTable = @{
  Key1 = 'Value1'
}
$hashTable += @{Key2 = 'Value2'}
$hashTable
1
#Output
1
2
3
Name Value
---- -----
Key1 Value1
1
Key2 Value2

An example, to add a "Key2" key with a value of "Value2" to the hash table using the Add method:

1
2
3
4
5
$hashTable = @{
Key1 = 'Value1'
}
$hashTable.Add("Key2", "Value2")
$hashTable
1
#Output
1
2
3
4
Name Value
---- -----
Key1 Value1
Key2 Value2

10.4: Remove a key value pair from an existing hash table

An example, to remove a "Key2" key with a value of "Value2" from the hash table, using the remove operator:

1
2
3
4
5
6
$hashTable = @{
  Key1 = 'Value1'
  Key2 = 'Value2'
}
$hashTable.Remove("Key2", "Value2")
$hashTable
1
#Output
1
2
3
Name Value
---- -----
Key1 Value1

10.5: Enumerating through keys and Key-Value Pairs

Enumerating through Keys

1
2
3
4
5
foreach ($key in $var1.Keys) {
  $value = $var1[$key]
  # or
  $value = $var1.$key
}

Enumerating through Key-Value Pairs

1
2
3
4
foreach ($keyvaluepair in $var1.GetEnumerator()) {
  $key1 = $_.Key1
  $val1 = $_.Val1
}

10.6: Looping over a hash table

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
$hashTable = @{
  Key1 = 'Value1'
  Key2 = 'Value2'
}

foreach($key in $hashTable.Keys)
{
  $value = $hashTable.$key
  **Write-Output** "$key : $value"
}

#Output
Key1 : Value1
Key2 : Value2