Understanding PowerShell Hash Tables

Kaan ARA
2 min readApr 25, 2023

--

In PowerShell, a hash table is a collection of key-value pairs. Each key in the hash table must be unique, and the values can be of any type. Hash tables are useful for storing and retrieving data quickly based on a specific key.

Creating a Hash Table

To create a hash table in PowerShell, you use the @{} syntax with each key-value pair separated by commas. Here's an example:

$hashTable = @{
"Name" = "John"
"Age" = 30
}

In this example, we’re creating a hash table with two key-value pairs. The first key is "Name" and its value is "John". The second key is "Age" and its value is 30.

Accessing Values in a Hash Table

You can access the values in a hash table using their keys like this:

$hashTable["Name"]

This will return the value associated with the "Name" key, which in this case is "John".

Adding or Updating Values in a Hash Table

You can add or update values in a hash table like this:

$hashTable["City"] = "New York"

This adds a new key-value pair to the hash table with the key "City" and the value "New York". If there was already a key called "City", this would update its value instead.

Removing Key-Value Pairs from a Hash Table

To remove a key-value pair from a hash table, you can use the Remove method like this:

$hashTable.Remove("Age")

This removes the key-value pair with the key "Age" from the hash table.

Iterating Over Keys and Values in a Hash Table

Finally, you can iterate over all the keys and values in a hash table using a foreach loop like this:

foreach ($key in $hashTable.Keys) {
Write-Host "$key: $($hashTable[$key])"
}

This will output each key-value pair in the hash table on its own line.

Conclusion

Hash tables are an important data structure to understand when working with PowerShell. They allow you to store and retrieve data quickly based on specific keys. With these basic concepts under your belt, you’ll be able to work more effectively with PowerShell scripts that utilize hash tables.

--

--