PowerShell: How to Add Values to Hash Table


Often you may want to add values to a hash table in PowerShell.

You can use the following methods to do so:

Method 1: Add New Element to Hash Table

$my_hash.add('A0006', 'Great')

This particular example adds a new element to the end of the hash table named $my_hash with the key ‘A0006‘ and the value ‘Great‘.

Method 2: Append Value to Existing Element in Hash Table

$my_hash.A0003 += 'est'

This particular example appends the text ‘est’ to the end of the existing value in the hash table named $my_hash that has a key of A0003.

The following examples show how to use each method in practice with the following hash table named $athletes that contains keys that represent athlete ID numbers on some basketball team and values that represent their status as an athlete:

$athletes = [ordered]@{
  'A0001' = 'Good';
  'A0002' = 'Great';
  'A0003' = 'Great';
  'A0004' = 'OK';
  'A0005' = 'Bad';
}

Example 1: How to Add New Element to Hash Table

We can use the following syntax to add a new element to the end of the hash table named $athletes that contains the key A0006 and a value of ‘Great‘:

$athletes.add('A0006', 'Great') 

The following screenshot shows how to use this syntax in practice:

PowerShell add values to hash table

Notice that when we view the updated $athletes hash table we can see that a new element has been added to the end of the table with a key of A0006 and a value of Great.

Example 2: How to Append Value to Existing Element in Hash Table

We can use the following syntax to append the text ‘est’ to the end of the existing element in the hash table named $my_hash that has a key of A0003:

$my_hash.A0003 += 'est'

The following screenshot shows how to use this syntax in practice:

PowerShell append value to existing element in hash table

Notice that ‘est‘ has been added to the value of the existing element with the key A0003 in the hash table so that it now has a value of Greatest.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Check if Hash Table Contains Specific Key
PowerShell: How to Iterate Over a Hash Table
PowerShell: How to Remove Elements from a Hash Table
PowerShell: How to Update Values in Hash Table

Leave a Reply