Skip to main content

How to Create a Hashtable in PowerShell

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

A hashtable stores values under names you choose, called keys, so you can look a value up by its name. In PowerShell you write one with an at sign and braces, as in @{ France = 'Paris' }. This guide creates a hashtable of capitals, reads, adds and removes values, and keeps the keys in order, with real output from PowerShell 7.6.10.

The about_Hash_Tables page defines it: "A hashtable, also known as a dictionary or associative array, is a compact data structure that stores one or more key-value pairs."

Syntax​

Syntax
$<variable> = @{
<key1> = <value1>
<key2> = <value2>
}
$<variable>['<key>']
$<variable>.<key>
PartWhat it means
$<variable> =Saves the hashtable in a variable, so you can use it later
@{ and }Begin and end the hashtable
<key> = <value>One key-value pair: a key, an equal sign, then the value stored under that key
A line break or ;Separates one pair from the next
$<variable>['<key>']Reads the value stored under a key: the key goes in square brackets, in quotes
$<variable>.<key>Reads the same value with a dot and the key's name

The about_Hash_Tables page lists the rules, among them: "Begin the hashtable with an at sign (@).", "Enclose the hashtable in braces ({}).", "Use an equal sign (=) to separate each key from its value." and "Use a semicolon (;) or a line break to separate the key-value pairs." It adds: "Keys that contain spaces must be enclosed in quotation marks. Values must be valid PowerShell expressions. Strings must appear in quotation marks, even if they don't include spaces."

The Example​

The example stores three countries and their capitals: each country is a key, and its capital is the value stored under it. The commands run in the PowerShell 7.6.10 console.

Prerequisites​

  • PowerShell 7. This guide uses PowerShell 7.6.10: $PSVersionTable.PSVersion.ToString() printed 7.6.10.

Step 1: Create a Hashtable​

Type the hashtable over several lines, then the variable's name on its own to print it:

PowerShell
$capitals = @{
France = 'Paris'
Japan = 'Tokyo'
Kenya = 'Nairobi'
}
$capitals

macOS-style code window titled PowerShell that saves a hashtable in $capitals, with the three key-value lines France = 'Paris', Japan = 'Tokyo' and Kenya = 'Nairobi', then prints it with $capitals on the last line.

Output
Name Value
---- -----
Japan Tokyo
Kenya Nairobi
France Paris

The at sign and the opening brace start the hashtable, and the closing brace ends it. Each line between them is one pair: the key, =, and the value in quotes, because it's text. While the brace is open, the console starts each new line with >>, waiting for the rest. Typing $capitals on its own printed the hashtable as a table, with the keys under Name and the values under Value.

The pairs came out as Japan, Kenya, France, not in the order you typed them. The about_Hash_Tables page: "As you can see, the key-value pairs in a hashtable aren't presented in the order that they were defined." Step 4 keeps the order.

Step 2: Read a Value by Its Key​

PowerShell
$capitals['Japan']
$capitals.Kenya
$capitals.Count
Output
Tokyo
Nairobi
3

macOS-style terminal window titled PowerShell where $capitals is typed over five lines that start with >>, printed as a Name and Value table in the order Japan, Kenya, France, and then $capitals['Japan'] prints Tokyo, $capitals.Kenya prints Nairobi and $capitals.Count prints 3.

The key in square brackets returned the value stored under it, Tokyo. A dot and the key's name did the same for Kenya. The about_Hash_Tables page calls these array index notation and member notation, and says: "When you use index notation with hashtables, the value inside of the brackets is the key name. If the key is a string value, enclose the key name in quotes."

Count is a property every hashtable has: the number of key-value pairs, 3 here.

Step 3: Add, Change and Remove Values​

A hashtable can also be written on one line, with a semicolon between the pairs. Assigning a value to a key that isn't there yet adds the key:

PowerShell
$capitals = @{ France = 'Paris'; Japan = 'Tokyo'; Kenya = 'Nairobi' }
$capitals['Peru'] = 'Lima'
$capitals.Count
$capitals.Keys
Output
4
France
Peru
Japan
Kenya

Count went up to 4, and Keys, the list of every key, now includes Peru. The about_Hash_Tables page: "You can add key-value pairs using array notation."

Assigning to a key that's already there replaces its value instead. This hashtable starts with the wrong capital for France, which the second line fixes, and Remove() deletes Kenya's pair:

PowerShell
$capitals = @{ France = 'Lyon'; Japan = 'Tokyo'; Kenya = 'Nairobi' }
$capitals['France'] = 'Paris'
$capitals['France']
$capitals.Remove('Kenya')
$capitals.Count
Output
Paris
2

France now holds Paris. Remove() printed nothing, and Count dropped to 2. The page: "You can't use a subtraction operator to remove a key-value pair from a hashtable, but you can use the Remove() method of the hashtable object."

Step 4: Keep the Keys in the Order You Typed Them​

Put [ordered] straight before the @:

PowerShell
$capitals = [ordered]@{
France = 'Paris'
Japan = 'Tokyo'
Kenya = 'Nairobi'
}
$capitals
$capitals.GetType().FullName
Output
Name Value
---- -----
France Paris
Japan Tokyo
Kenya Nairobi

System.Collections.Specialized.OrderedDictionary

The pairs printed in the order typed. GetType().FullName names the type PowerShell made: an OrderedDictionary, while the page says "In PowerShell, each hashtable is a [System.Collections.Hashtable] object." It explains the difference: "Ordered dictionaries differ from hashtables in that the keys always appear in the order in which you list them. The order of keys in a hashtable isn't deterministic." And: "You can use ordered dictionaries in the same way that you use hashtables."

Common Mistakes​

MistakeWhat happensDo this instead
Commas between the pairs: @{ France = 'Paris', Japan = 'Tokyo' }ParserError: Missing expression after ','.Separate the pairs with ; or a new line
A colon instead of =: @{ France: 'Paris' }ParserError: Missing '=' operator after key in hash literal.Put = between the key and the value
A key with a space and no quotes: @{ Saint Lucia = 'Castries' }The same Missing '=' operator after key in hash literal.Quote the key: with @{ 'Saint Lucia' = 'Castries' }, $capitals['Saint Lucia'] returned Castries
The same key twice: @{ France = 'Paris'; France = 'Lyon' }ParserError: Duplicate keys 'France' are not allowed in hash literals.Write each key once, and change a value by assigning to its key, as in Step 3

Troubleshooting​

SymptomLikely causeFix
A key returns nothingThe key isn't in the hashtableCheck its spelling: $capitals.Keys lists every key
Exception calling "Add" with "2" argument(s): "Item has already been added. Key in dictionary: 'France' Key being added: 'France'"Add() was given a key the hashtable already hasAssign to the key instead, which replaces its value

FAQ​

What do I get for a key that isn't there?​

Nothing, and no error: $capitals['Spain'] printed nothing, and $null -eq $capitals['Spain'] returned True.

Do keys care about upper and lower case?​

Not in a hashtable written with @{}: $capitals['japan'], in lower case, returned Tokyo. The about_Case-Sensitivity page: "[hashtable]::new() has case-sensitive keys, whereas a hashtable literal @{} has case-insensitive keys."

Can I add a key with the Add() method?​

Yes, when the key is new: $capitals.Add('Peru', 'Lima') added Peru, and $capitals['Peru'] returned Lima. The about_Hash_Tables page: "You can also add keys and values to a hashtable using the Add() method of the System.Collections.Hashtable object." For a key that's already there, Add() fails with the exception in the Troubleshooting table, while assigning to the key replaces the value.

Conclusion​

@{ France = 'Paris'; Japan = 'Tokyo'; Kenya = 'Nairobi' } made a hashtable of three capitals, and $capitals['Japan'] returned Tokyo. Separate the pairs with ; or new lines, put text values and keys with spaces in quotes, and put [ordered] before the @ when the order matters.

Additional Resources​