Create PowerShell Hashtable
PowerShell Hashtables are compact data structures, which are very popular and come handy in a lot of use cases. They are capable to store one or more Key-Value
pairs and today we are going to looking into various approaches and methods to create a Hashtable in PowerShell:
-
Using
@{ }
The simplest way to create a hashtable is using
@
followed by curly-bracket pair, where brackets define the body of hashtable wherekey-value
pairs can be defined separated by anEqualsTo
sign=
as demonstrated in the following example
-
Using
.Net
class for Hashtable withNew-Object
cmdletAll the Hashtables you create using the above method would be created as an object
.Net
classSystem.Collections.Hashtable
, that means you can use this class and instantiate it using the cmdletNew-Object
to create a Hashtable. -
Using
[Hashtable]
PowerShell Type AcceleratorWe can also use the PowerShell Type accelerator of the
.Net
class withNew()
method to create an instance of the Hashtable object, which will save us from some extra typing and definitely looks neat, like in the following example: -
Using
[Ordered]
DictionarySince
PowerShell v3.0
, you can now also use the[Ordered]
attribute to create an Ordered Dictionary which makes sure keys appear in the order in which they are defined, under the hoods, this is forcing the hashtable to be created using the class[System.Collections.Specialized.OrderedDictionary]
instead of[System.Collections.Hashtable]
.Now, we know that this class exists, it can be directly used to create Hashtables that will be ordered.
-
Using
[System.Collections.Generic.Dictionary[KeyType,ValueType]]
To be honest, I’m cheating here a little, Dictionary and Hashtable are two different data structures, but they are very identical as both of them store a Key-Value pair, but dictionaries are
Strongly typed
unlike PowerShell[Hashtables]
, which means in a Dictionary if a key\value is defined to store an [int] value you can not add any other data type, otherwise you will run into errors.Dictionaries are usually faster because there is no boxing and unboxing happening like a Hashtable in PowerShell. In the following example, we are using the
System.Collections.Generic.Dictionary[String,String]
class with data type for key and the value to create a dictionary object. -
Using
[Dictionary]
PowerShell Type AcceleratorYou can use the PowerShell type accelerator of the
System.Collections.Generic.Dictionary
Class withNew()
method to create your dictionaries. -
From
[PSObject]
by iterating properties & addingKey-Value
pairsWe can access the properties of PowerShell Objects
[PSObject]
, and iterate each property and its value and feed them in a Hashtable to initialize one, like in the following example. -
[String]
to[Hashtable]
usingConvertFrom-StringData
cmdletHashtables are very popular in efficiently finding and retrieving data, and cmdlets like
ConvertFrom-StringData
make it further easy to extract data from a string directly into a hashtable as demonstrated in the following example. This approach will save you some extra typing and use of punctuations. -
From
[String]
using-Match
operator andRegEx
When dealing with strings data or information from a file, you can use the combination of a
Regular Expressions
and-Match
operator to extract Key and Value pairs from data, which can be used to initialize and create Hashtables in PowerShell, this is one of my favorite ways to build a hashtable from a Log (*.log
) or Settings (*.INI
) file. -
Using
Group-Object
Cmdlet’s'-AsHashTable'
switch parameterYou can use the
-AsHashTable
switch parameter ofGroup-Object
cmdlet to convert[Microsoft.PowerShell.Commands.GroupInfo]
objects to[System.Collections.Hashtable]
-
Using
ConvertFrom-JSON
Cmdlet’s'-AsHashTable'
switch parameterSince PowerShell
v6.2
,ConvertFrom-JSON
cmdlet also supports'-AsHashTable'
switch parameter, which can be useful in a lot of scenarios. I was not aware of this, thanks to Kevin Marquette for this tip!
Following are all the example we discussed in the above section which I could think of, let me know in case you know more in comments and I’ll add them into this article with credits. Thank you.
Examples:
If you like this article read more similar articles under ‘N – Ways to’ category
- 3 ways to UnZip Compressed Files using PowerShell
- 4 ways to send output to NULL in PowerShell
- 3 Ways to Create Custom TypeNames on PowerShell Objects
- 3 ways to store and display PowerShell Variable simultaneously
- 4 ways to select Unique items in PowerShell
- 4 Ways to Create PowerShell Objects
- 2 Ways to Copy Files from Windows 10 to Windows Sub-System for Linux
~ Author of “PowerShell Guide to Python“, and currently writing a Book on “Windows Subsystem for Linux (WSL)“
All my books are available as a discounted bundle:
-
- PowerShell Guide to Python : This PowerShell Scripting guide to Python is designed to make readers familiar with syntax, semantics and core concepts of Python language, in an approach that readers can totally relate with the concepts of PowerShell already in their arsenal, to learn Python fast and effectively, such that it sticks with readers for longer time.
- Windows Subsystem for Linux (WSL) : Keywords, definitions, and problems WSL solve and how it works under the hoods. From download to setup to interoperability this book even covers details like the architecture of Windows subsystem for Linux and new features in WSL 2 with some wonderful use cases.
Prateek Singh
Related posts
4 Comments
Leave a ReplyCancel reply
Categories
Author of Books
Awards
Open Sourced Projects
Author at
Blog Roll
Mike F RobbinsDamien Van Robaeys
Stéphane van Gulick
Kevin Marquette
Adam Bertram
Stephanos Constantinou
Francois-Xavier Cat
Ravikanth Chaganti
Roman Levchenko
Blog Stats
- 1,132,338 People Reached
Prateek, first of all this is a great (and thorough) look at hashtables in PowerShell. You may want to correct your example output for 8. I believe it should be:
Name Value
—- —–
skills powershell
age 29
name prateek
Thanks,
Alain
Using [System.Management.Automation.PSPrimitiveDictionary] or its type accelerator
$pd = [psprimitivedictionary]::new()
This is insightful! I had one question, though.
Is it possible to define (declare and insert elements) in a dictionary with this syntax?
$myDict = [System.Collections.Generic.Dictionary[String,String]]::new()
I’m asking this because it’s possible to do so with Lists.
$myList = [System.Collections.Generic.List[String]](“Apple”,”Ball”,”Cat”)
[…] + Read More […]