How to Create a Hashtable in PowerShell?

Hashtables enable you to store key-value pairs efficiently in PowerShell. Whether managing user data, configurations, or any other structured information, you can use a hashtable in PowerShell. In this tutorial, I will explain how to create and use hashtables in PowerShell with detailed examples.

What is a Hashtable in PowerShell?

A hashtable, also known as a dictionary or associative array, is a collection of key-value pairs. Each key in a hashtable is unique and is used to retrieve the corresponding value. This makes hashtables incredibly useful for scenarios where you need to quickly look up data.

Why Use Hashtables in PowerShell?

There are various advantages to using hashtables in PowerShell. Here are a few:

  • Efficiency: Quick lookups and modifications.
  • Flexibility: Can store different types of values.
  • Readability: Makes scripts easier to understand and maintain.

Create a Hashtable in PowerShell

In PowerShell, it is easy to create a hashtable. You use the @{} syntax to define a hashtable. Here is an example.

$person = @{
    Name = "John Doe"
    Age = 30
    City = "New York"
}

In this example, we created a hashtable named $person with three key-value pairs: Name, Age, and City.

Check out Convert String to Hashtable in PowerShell

Access Hashtable Values in PowerShell

To access the values in a hashtable, you use the key associated with the value. Here is the complete PowerShell script:

$person = @{
    Name = "John Doe"
    Age = 30
    City = "New York"
}
$personName = $person["Name"]
$personAge = $person["Age"]
$personCity = $person["City"]

Write-Output "Name: $personName"
Write-Output "Age: $personAge"
Write-Output "City: $personCity"

This script will output:

Name: John Doe
Age: 30
City: New York

I executed the above PowerShell script, and you can see the output in the screenshot below:

Create a Hashtable in PowerShell

Read PowerShell Hashtable vs Array

Add and Modify Hashtable Elements in PowerShell

Now, let me show you how to add and modify elements in a hashtable in PowerShell. You can easily add new entries or modify existing ones in a hashtable.

Add a New Element

Below is how to add a new element in a Hashtable in PowerShell.

$person["State"] = "New York"

Modify an Existing Element

Here is how to modify an existing element in a hashtable in Python.

$person["City"] = "Los Angeles"

Now, the $person hashtable will look like this:

@{
    Name = "John Doe"
    Age = 30
    City = "Los Angeles"
    State = "New York"
}

Remove Elements from a Hashtable

To remove an entry from a hashtable, use the PowerShell Remove method.

$person.Remove("State")

After removing the State entry, the hashtable will be:

@{
    Name = "John Doe"
    Age = 30
    City = "Los Angeles"
}

Read PowerShell Array of Hashtables

Iterate Over a Hashtable in PowerShell

You can iterate over a hashtable using a foreach loop to process each key-value pair.

$person = @{
    Name = "John Doe"
    Age = 30
    City = "New York"
}

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

This will output:

Name: John Doe
Age: 30
City: Los Angeles

Here is the exact output in the screenshot below:

PowerShell Create a Hashtable

Read Create and Manipulate Lists in PowerShellCreate and Use Dictionaries in PowerShell?

PowerShell Hashtable Real Example

Now, let me show you how to use a hashtable in PowerShell with a real example.

Example: User Data Management

Imagine you are managing user data for a USA-based company. You need to store and retrieve user information efficiently. Then you can write a PowerShell script like below:

$users = @{}

# Adding users
$users["jdoe"] = @{
    Name = "John Doe"
    Age = 30
    City = "New York"
    Email = "jdoe@example.com"
}

$users["asmith"] = @{
    Name = "Alice Smith"
    Age = 28
    City = "San Francisco"
    Email = "asmith@example.com"
}

# Retrieving user data
$user = $users["jdoe"]
Write-Output "Name: $($user["Name"])"
Write-Output "Email: $($user["Email"])"

This script stores user data in a hashtable and retrieves it using the username as the key.

Nested Hashtable in PowerShell

Hashtables can contain other hashtables, allowing for complex data structures. These are called nested hashtables. Here is an example of a nested hashtable in PowerShell.

$company = @{
    Name = "TechCorp"
    Location = "Silicon Valley"
    Employees = @{
        "jdoe" = @{
            Name = "John Doe"
            Position = "Developer"
        }
        "asmith" = @{
            Name = "Alice Smith"
            Position = "Manager"
        }
    }
}

# Accessing nested hashtable
$employee = $company["Employees"]["jdoe"]
Write-Output "Employee Name: $($employee["Name"])"
Write-Output "Position: $($employee["Position"])"

Read Create and Use Dictionaries in PowerShell

PowerShell Hashtable Methods

PowerShell hashtables come with built-in methods for managing entries. Let me show you a few useful methods with examples.

ContainsKey

This method checks if a key exists in the hashtable in PowerShell.

if ($person.ContainsKey("Age")) {
    Write-Output "Age is present"
}

GetEnumerator

This method returns an enumerator for iterating over the hashtable. Here is an example.

$enumerator = $person.GetEnumerator()
while ($enumerator.MoveNext()) {
    $entry = $enumerator.Current
    Write-Output "$($entry.Key): $($entry.Value)"
}

Conclusion

In this tutorial, I explained how to create and use hashtables in PowerShell with some examples. Hashtables are used to handle key-value pairs in PowerShell. I have also explained a few examples of using hashtables in PowerShell.

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.