Using the Add Method of a Hashtable Object

I saw an interesting approach to working with a hashtable the other day. It started with this:

$hashtable = @{}

This is different than how I usually create an array:

$array = @()

And also different from creating a PowerShell object:

$PSObject = [PSCustomObject]@{}

There are some real advantages to using a PSCustomObject instead of a hashtable. But if all you need to do is quickly and easily store a collection of name/key values, the “Add()” method of the hashtable object is pretty handy.

Here’s how it works.

$hashtable = @{}


Compared to adding properties to a PSCustomObject with the Add-Member cmdlet, using the Add method is very appealing. It’s quick and to the point.

Just to be clear, I’m not advocating for the wide use of hashtables instead of PSCustomObjects. I think PSCustomObjects are the better structure, especially in a case where you’re creating multiple objects or later working with the objects to sort, select or output the data.

But in a case where you just want to very quickly and easily add some data into a table inside your script and then reference it later, then the Add method of the hashtable is super easy.

When working with most basic operations, working with the hashtable will be similar to working with properties on an object.

"My name is $($ and I have $($hashtable.eyes) eyes."