Home » PowerShell Hashtables

PowerShell Hashtables

A hashtable is a data structure, similar to an array but you store each object using a key. It’s stored as key/value pairs in a hash table. The key and value can be any object type. Commonly, we used integers or strings as keys in the hash table.

In this article, we will discuss PowerShell hashtables, and how to declare and use them in PowerShell.

How to Declare a HashTable in PowerShell

To declare a hashtable in PowerShell, use the @{} syntax. It will create an empty hashtable.

# Creating a hashtable
$students = @{}

How to Create Hashtable with Values

To create a hashtable with values, you can pre-populate the keys and values when you create a hashtable.

The following script creates a hashtable $studentsPercentage and stores the student’s name as keys and percentage as values in the hashtable.

# pre-populate the key-value pairs in hashtable
$studentsPercentage = @{
Tom = 89
Akshada = 75
}

The output of the above script is:

PS D:\ps> $studentsPercentage                                                                                                                                                                
Name                           Value
----                           -----
Akshada                        75
Tom                            89

How to Add Items to a HashTable in PowerShell

To add items to a hashtable, use the Add() method.

# Create a hashtable
$students = @{}

# Add items to a hashtable

$students.Add(1, "Tom")
$students.Add(2, "Akshada")
$students.Add(3, "Adam")

The output of the above PowerShell scripts creates a hashtable $students having Id (integer type) as the key and Name (string type) as the value stored in it.

Print the hashtable to see the key/value pairs stored in it.

PS D:\ps> $students

Name                           Value
----                           -----
3                              Adam
2                              Akshada
1                              Tom

How to Get All Keys from a Hashtable in PowerShell

To get all keys from a hashtable use .keys syntax with a hashtable.

The following PowerShell script will print all the keys of a hashtable.

$students.keys

Result

PS D:\ps> $students.keys
3
2
1

How to Retrieve All Values from a Hashtable in PowerShell

Use the .Values syntax with a hashtable variable to get all values from a hashtable in PowerShell.

$students.Values

Result

Adam
Akshada
Tom

How to Access the Items from a Hashtable in PowerShell

To access the items from the hashtable in PowerShell, you can specify the key. It will return the value associated with the given key in a hashtable.

# retrieve data from a hashtable using the key
$students[1]

The output of the above PowerShell script gets value from a hashtable by key.

PS D:\ps> $students[1]
Tom

How to Loop Through a Hashtable

You can iterate a hashtable in different ways and access its key-value pairs from the collections.

$studentsPercentage.GetEnumerator()  | ForEach-Object{
    $msg = 'Student {0} has scored {1} percentages'
    Write-Output $msg
}

In the above PowerShell script, the GetEnumerator() method is used for iterating over the hashtable the $studentsPercentage. The enumerator gets each key/value pair from the collection and pipes it to the ForEach-Object loop for iteration.

The output of the above PowerShell script is given below.

Student Akshada has scored 75 percentages
Student Tom has scored 89 percentages
                                                                                                                      

You can enumerate the keys of the hashtable and use them to access the values.

$students.Keys | ForEach-Object 
{ 
    Write-Host "Student ID $($_) : $($students[$_])"
}

Result

PS D:\ps> $students.Keys | ForEach-Object { Write-Host "Student ID $($_) : 
$($students[$_])"}

Student ID 3 : Adam
Student ID 2 : Akshada
Student ID 1 : Tom
PS D:\ps>   

How to Update Hashtable Values

To update the hashtable values, use the key to select the key/value pair.

$studentsPercentage['Akshada'] = 77  

In the above PowerShell script, we have used the index (key) to update the $studentsPercentage hashtable value.

The output of the above script after updating hashtable values using the index is:

PS D:\ps> $studentsPercentage                                                                                           
Name                           Value
----                           -----
Akshada                        75
Tom                            89


PS D:\ps> $studentsPercentage['Akshada'] = 77                                                                           PS D:\ps> $studentsPercentage                                                                                           
Name                           Value
----                           -----
Akshada                        77
Tom                            89


PS D:\ps>                                                                                                                                                                                                                                                      

How to Remove Keys from a Hashtable Using PowerShell

To remove a key/value pair from a hashtable, you can use the .remove() method.

The following script deletes keys from a hashtable as specified in the remove() method.

$studentsPercentage.Remove('Akshada')   

The above command will remove a key named ‘Akshada‘ from a hashtable $studentsPercentage.

How to Clear a Hashtable Using PowerShell

To clear a hashtable using the PowerShell, use the Clear() method. The Clear() will remove all key/value pairs from a hash table.

$studentsPercentage.Clear()

How to Sort a Hashtable Using PowerShell

To sort a hashtable by its key (index) in a PowerShell, enumerate the keys in a hash table and pipe the result to the Sort-Object cmdlet. The Sort-Object command uses the property Key to sort the hashtable by key.

$students.GetEnumerator() | Sort-Object -Property Key   

Result

PS D:\ps> $students.GetEnumerator() | Sort-Object -Property Key                                                         
Name                           Value
----                           -----
1                              Tom
2                              Akshada
3                              Adam


PS D:\ps>  

Create Custom Objects From Hashtables

To create an object from the hashtable in PowerShell, use the [PSCustomObject] in front of the hash table.

$students_object = [PSCustomObject]@{ 
Tom = 89
Akshada = 75
}

Result

PS D:\ps> $students_object                                                                                              
Tom Akshada
--- -------
 89      75

How to Count Items in Hashtable in PowerShell

To count items in a hashtable, use the Count property.

$students.Count

Result

PS D:\ps> $students.Count                                                                                               
3

How to Check If Hashtable Contains a Key in PowerShell

To check if a Hashtable contains a key in PowerShell, use the .ContainKey() method within the if statement.

$key = 'Tom'                                                                                                  if($studentsPercentage.ContainsKey($key)) 
{
   Write-Host "key $key exists in the hashtable."
} Else
{
   Write-Host "key $key does not exists in the hashtable."
}                                                             

Result

key Tom exists in the hashtable.
   

Cool Tip: How to use array in PowerShell!

Conclusion

I hope the above article on the PowerShell hashtable topic is helpful to you.

The Hashtable is very useful when you want to store structured data. Once you have a key/value pair stored in the hashtable, you can use the GetEnumerator() method or Foreach loop well to iterate over the items or use an index to access the individual elements in the hashtable.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.