Making better use of HashTables in PowerShell

This article will help you understand what HashTables are and how to use them in PowerShell.

What are HashTables?

HashTables are used for saving Key-Value pairs, where each Key must be unique, whereas their corresponding values may not be unique.


Here is the syntax for creating a HashTable:

$ht = @{"Name"="Savindra"; "Age"=33; "Department"="IT"; "City"="Hyderabad"}

When you see the output of the above command by giving $ht, you will notice that the order of the output is not same as we have provided.


With PowerShell Version 3.0 onwards you can preserve the order of properties of the HashTable by using [Ordered] with the HashTable like this:

$ht = [Ordered]@{"Name"="Savindra"; "Age"=33; "Department"="IT"; "City"="Hyderabad"}

This will preserve the order in which you have supplied the values in the HasTable. This time you will notice that the order of properties in input and output is same:


Why are HashTables useful?

Since HashTables can store any kind of values including objects/arrays/HashTables etc., they are great for using within your scripts for providing an output, especially when you want to have some kind of hierarchical output. You can easily convert the HashTables into PSCustomObjects before writing them as output. I will show you two different ways of converting the HashTables into PSCustomObject which is a good way for passing the output to next command in the pipeline.

1. Longer way:

$objOut = New-Object -TypeName PSCustomObject -Property $ht

This will give us a variable which will return a PSCustomObject as shown below:PipeLineOutput.png

However, this same result can be achieved using an easy and shorter way by type casting the HashTable while creating it.

2. in single step:

$objOut = [PSCustomObject][Ordered]@{"Name"="Savindra"; "Age"=33; "Department"="IT"; "City"="Hyderabad"}

I hope this is informative for you. Please let me know if you have any queries.

Thank you for reading this post.

Comments (1)

Qlemo"Batchelor", Developer and EE Topic Advisor
Top Expert 2015

Note that starting with PS 4 you do not need to use [Ordered] with [PSCustomObject], as the sequence gets preserved already.
And there is a lot more to say about hashtables, of course ...

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.

Get access with a 7-day free trial.
You Belong in the World's Smartest IT Community