- Article
Short description
Describes how to create, use, and sort hashtables in PowerShell.
Long description
A hashtable, also known as a dictionary or associative array, is a compact datastructure that stores one or more key-value pairs. For example, a hash tablemight contain a series of IP addresses and computer names, where the IPaddresses are the keys and the computer names are the values, or vice versa.
In PowerShell, each hashtable is a [System.Collections.Hashtable]
object. Youcan use the properties and methods of Hashtable objects in PowerShell.
Beginning in PowerShell 3.0, you can use the [ordered]
type accelerator tocreate an [System.Collections.Specialized.OrderedDictionary]
object inPowerShell.
Ordered dictionaries differ from hashtables in that the keys always appear inthe order in which you list them. The order of keys in a hashtable isn'tdeterministic.
The keys and value in hashtables are also .NET objects. They're most oftenstrings or integers, but they can have any object type. You can also createnested hashtables, in which the value of a key is another hashtable.
Hashtables are frequently used because they're efficient for finding andretrieving data. You can use hashtables to store lists and to create calculatedproperties in PowerShell. And, the ConvertFrom-StringData
cmdlet convertsstructured string data to a hashtable.
Syntax
The syntax of a hashtable is as follows:
@{ <name> = <value>; [<name> = <value> ] ...}
The syntax of an ordered dictionary is as follows:
[ordered]@{ <name> = <value>; [<name> = <value> ] ...}
The [ordered]
type accelerator was introduced in PowerShell 3.0.
To create a hashtable, follow these guidelines:
- Begin the hashtable with an at sign (
@
). - Enclose the hashtable in braces (
{}
). - Enter one or more key-value pairs for the content of the hashtable.
- Use an equal sign (
=
) to separate each key from its value. - Use a semicolon (
;
) or a line break to separate the key-value pairs. - Keys that contain spaces must be enclosed in quotation marks. Values must bevalid PowerShell expressions. Strings must appear in quotation marks, even ifthey don't include spaces.
- To manage the hashtable, save it in a variable.
- When assigning an ordered hashtable to a variable, place the
[ordered]
typebefore the@
symbol. If you place it before the variable name, the commandfails.
You can use ordered dictionaries in the same way that you use hashtables.Either type can be used as the value of parameters that take a hashtable ordictionary (iDictionary) type objects.
Creating hashtables and ordered dictionaries
Consider the following hashtable and ordered dictionary examples:
$hash = @{ 1 = 'one' 2 = 'two' 'three' = 3}$hash
Name Value---- -----three 32 two1 one
As you can see, the key-value pairs in a hashtable aren't presented in theorder that they were defined.
The easiest way to create an ordered dictionary is to use the [ordered]
attribute. Place the attribute immediately before the @
symbol.
$dictionary = [ordered]@{ 1 = 'one' 2 = 'two' 'three' = 3}$dictionary
Name Value---- -----1 one2 twothree 3
Unlike hashtables, ordered dictionaries maintain the order of the key-value.
Converting hashtables and ordered dictionaries
You can't use the [ordered]
type accelerator to convert or cast a hashtable.If you place the ordered attribute before the variable name, the command failswith the following error message.
[ordered]$orderedhash = @{}ParserError:Line | 1 | [ordered]$orderedhash = @{} | ~~~~~~~~~~~~~~ | The ordered attribute can be specified only on a hash literal node.
To correct the expression, move the [ordered] attribute.
$orderedhash = [ordered]@{}
You can cast an ordered dictionary to a hashtable, but you can't guarantee theorder of the members.
[hashtable]$newhash = [ordered]@{ Number = 1 Shape = "Square" Color = "Blue"}$newhash
Name Value---- -----Color BlueShape SquareNumber 1
Hashtable and dictionary properties
Hashtables and ordered dictionaries share several properties. Consider the$hash
and $dictionary
variables defined in the previous examples.
$hash | Get-Member -MemberType Properties, ParameterizedProperty
TypeName: System.Collections.HashtableName MemberType Definition---- ---------- ----------Item ParameterizedProperty System.Object Item(System.Object key) {get;set;}Count Property int Count {get;}IsFixedSize Property bool IsFixedSize {get;}IsReadOnly Property bool IsReadOnly {get;}IsSynchronized Property bool IsSynchronized {get;}Keys Property System.Collections.ICollection Keys {get;}SyncRoot Property System.Object SyncRoot {get;}Values Property System.Collections.ICollection Values {get;}
$dictionary | Get-Member -MemberType Properties, ParameterizedProperty
TypeName: System.Collections.Specialized.OrderedDictionaryName MemberType Definition---- ---------- ----------Item ParameterizedProperty System.Object Item(int index) {get;set;}, System.Object Item(System.Object key) {get;set;}Count Property int Count {get;}IsFixedSize Property bool IsFixedSize {get;}IsReadOnly Property bool IsReadOnly {get;}IsSynchronized Property bool IsSynchronized {get;}Keys Property System.Collections.ICollection Keys {get;}SyncRoot Property System.Object SyncRoot {get;}Values Property System.Collections.ICollection Values {get;}
The most-used properties are Count, Keys, Values, and Item.
The Count property that indicates the number of key-value pairs in theobject.
The Keys property is a collection of the key names in the hashtable ordictionary.
PS> $hash.Keysthree21PS> $dictionary.Keys12three
The Values property is a collection of the values in the hashtable ordictionary.
PS> $hash.Values3twoonePS> $dictionary.Valuesonetwo3
The Item property is a parameterized property that returns the value ofthe item that you specify. Hashtables use the key as the parameter to theparameterized property, while dictionaries use the index by default. Thisdifference affects how you access the values for each type.
Accessing values
There are two common ways to access the values in a hashtable or dictionary:member notation or array index notation.
Member notation - Values can be accessed by using the key name as amember property of the object. For example:
PS> $hash.1onePS> $dictionary.2two
Array index notation - Values can be accessed by using index notation.PowerShell converts that notation into a call to Item parameterizedproperty of the object.
When you use index notation with hashtables, the value inside of the bracketsis the key name. If the key is a string value, enclose the key name inquotes. For example:
PS> $hash['three']3PS> $hash[2]2
In this example, the key value
2
isn't an index into the collection ofvalues. It's the value of the key in the key-value pair. You can prove thisby indexing into the collection of values.PS> ([array]$hash.Values)[2]one
When you use index notation with dictionaries, the value inside of thebrackets is interpreted based on its type. If the value is an integer, it'streated as an index into the collection of values. If the value isn't aninteger, it's treated as the key name. For example:
PS> $dictionary[1]twoPS> ([array]$dictionary.Values)[1]twoPS> $dictionary[[object]1]onePS> $dictionary['three']3
In this example, the array value
[1]
is an index into the collection ofvalues using theItem(int index)
parameterized property overload. The arrayvalue[[object]1]
isn't an index but a key value using theItem(System.Object key)
overload.Note
This behavior can be confusing when the key value is an integer. Whenpossible, you should avoid using integer key values in dictionaries.
Handling property name collisions
If the key name collides with one of the property names of the HashTabletype, you can use the psbase intrinsic memberto access those properties. For example, if the key name is keys
and you wantto return the collection of the HashTable keys, use this syntax:
$hashtable.psbase.Keys
This requirement applies for other types that implement theSystem.Collections.IDictionary interface, like OrderedDictionary.
Iterating over keys and values
You can iterate over the keys in a hashtable to process the values in severalways. Each of the examples in this section has identical output. They iterateover the $hash
variable defined here:
$hash = [ordered]@{ Number = 1; Shape = "Square"; Color = "Blue"}
Note
In these examples, $hash
is defined as an ordered dictionary to ensure theoutput is always in the same order. These examples work the same for standardhashtables, but the order of the output isn't predictable.
Each example returns a message for every key and its value:
The value of 'Number' is: 1The value of 'Shape' is: SquareThe value of 'Color' is: Blue
This example uses a foreach
block to iterate over the keys.
foreach ($Key in $hash.Keys) { "The value of '$Key' is: $($hash[$Key])"}
This example uses ForEach-Object
to iterate over the keys.
$hash.Keys | ForEach-Object { "The value of '$_' is: $($hash[$_])"}
This example uses the GetEnumerator()
method to send each key-value pairthrough the pipeline to ForEach-Object
.
$hash.GetEnumerator() | ForEach-Object { "The value of '$($_.Key)' is: $($_.Value)"}
This example uses the GetEnumerator()
and ForEach()
methods to iterate overeach key-value pair.
$hash.GetEnumerator().ForEach({"The value of '$($_.Key)' is: $($_.Value)"})
Adding and Removing Keys and Values
Typically, when you create a hashtable you include the key-value pairs in thedefinition. However, you can add and remove key-value pairs from a hashtable atany time. The following example creates an empty hashtable.
$hash = @{}
You can add key-value pairs using array notation. For example, the followingexample adds a Time
key with a value of Now
to the hashtable.
$hash["Time"] = "Now"
You can also add keys and values to a hashtable using the Add()
method of theSystem.Collections.Hashtable object. The Add()
method has the followingsyntax:
Add(Key, Value)
For example, to add a Time
key with a value of Now
to the hashtable, usethe following statement format.
$hash.Add("Time", "Now")
And, you can add keys and values to a hashtable using the addition operator(+
) to add a hashtable to an existing hashtable. For example, the followingstatement adds a Time
key with a value of Now
to the hashtable in the$hash
variable.
$hash = $hash + @{Time="Now"}
You can also add values that are stored in variables.
$t = "Today"$now = (Get-Date)$hash.Add($t, $now)
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. TheRemove
method has the following syntax:
$object.Remove(<key>)
The following example removes the Time
key-value pair from $hash
.
$hash.Remove("Time")
Object Types in HashTables
The keys and values in a hashtable can have any .NET object type, and a singlehashtable can have keys and values of multiple types.
The following statement creates a hashtable of process name strings and processobject values and saves it in the $p
variable.
$p = @{ "PowerShell" = (Get-Process PowerShell) "Notepad" = (Get-Process notepad)}
You can display the hashtable in $p
and use the key-name properties todisplay the values.
PS> $pName Value---- -----PowerShell System.Diagnostics.Process (PowerShell)Notepad System.Diagnostics.Process (notepad)PS> $p.PowerShellHandles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName------- ------ ----- ----- ----- ------ -- ----------- 441 24 54196 54012 571 5.10 1788 PowerShellPS> $p.keys | ForEach-Object {$p.$_.handles}441251
The keys in a hashtable can be any .NET type. The following statement adds akey-value pair to the hashtable in the $p
variable. The key is a Serviceobject that represents the WinRM service, and the value is the current statusof the service.
$p = $p + @{ (Get-Service WinRM) = ((Get-Service WinRM).Status)}
You can display and access the new key-value pair using the same methods thatyou use for other pairs in the hashtable.
PS> $pName Value---- -----PowerShell System.Diagnostics.Process (PowerShell)Notepad System.Diagnostics.Process (notepad)System.ServiceProcess.Servi... RunningPS> $p.keysPowerShellNotepadStatus Name DisplayName------ ---- -----------Running winrm Windows Remote Management (WS-Manag...PS> $p.keys | ForEach-Object {$_.name}WinRM
The keys and values in a hashtable can also be Hashtable objects. The followingstatement adds key-value pair to the hashtable in the $p
variable in whichthe key is a string, Hash2, and the value is a hashtable with three key-valuepairs.
$p = $p + @{ "Hash2"= @{a=1; b=2; c=3}}
You can display and access the new values using the same methods.
PS> $pName Value---- -----PowerShell System.Diagnostics.Process (pwsh)Hash2 {[a, 1], [b, 2], [c, 3]}Notepad System.Diagnostics.Process (Notepad)WinRM RunningPS> $p.Hash2Name Value---- -----a 1b 2c 3PS> $p.Hash2.b2
Sorting Keys and Values
The items in a hashtable are intrinsically unordered. The key-value pairs mightappear in a different order each time that you display them.
Although you can't sort a hashtable, you can use the GetEnumerator()
methodof hashtables to enumerate the keys and values, and then use the Sort-Object
cmdlet to sort the enumerated values for display.
For example, the following commands enumerate the keys and values in the hashtable in the $p
variable and then sort the keys in alphabetical order.
PS> $p.GetEnumerator() | Sort-Object -Property keyName Value---- -----Hash2 {[a, 1], [b, 2], [c, 3]}Notepad System.Diagnostics.Process (Notepad)PowerShell System.Diagnostics.Process (pwsh)WinRM Running
The following command uses the same procedure to sort the hash values indescending order.
PS> $p.GetEnumerator() | Sort-Object -Property Value -DescendingName Value---- -----PowerShell System.Diagnostics.Process (pwsh)Notepad System.Diagnostics.Process (Notepad)Hash2 {[a, 1], [b, 2], [c, 3]}WinRM Running
Creating Objects from hashtables
Beginning in PowerShell 3.0, you can create an object from a hashtable ofproperties and property values.
The syntax is as follows:
[<class-name>]@{ <property-name>=<property-value> <property-name>=<property-value>}
This method works only for classes that have a constructor that has noparameters. The object properties must be public and settable.
For more information, see about_Object_Creation.
ConvertFrom-StringData
The ConvertFrom-StringData
cmdlet converts a string or a here-string ofkey-value pairs into a hashtable. You can use the ConvertFrom-StringData
cmdlet safely in the Data section of a script, and you can use it with theImport-LocalizedData
cmdlet to display user messages in the user-interface(UI) culture of the current user.
Here-strings are especially useful when the values in the hashtable includequotation marks. For more information about here-strings, seeabout_Quoting_Rules.
The following example shows how to create a here-string of the user messages inthe previous example and how to use ConvertFrom-StringData
to convert themfrom a string into a hashtable.
The following command creates a here-string of the key-value pairs and thensaves it in the $string
variable.
$string = @"Msg1 = Type "Windows".Msg2 = She said, "Hello, World."Msg3 = Enter an alias (or "nickname")."@
This command uses the ConvertFrom-StringData
cmdlet to convert thehere-string into a hashtable.
ConvertFrom-StringData $stringName Value---- -----Msg3 Enter an alias (or "nickname").Msg2 She said, "Hello, World."Msg1 Type "Windows".
For more information about here-strings, seeabout_Quoting_Rules.
See also
- about_Arrays
- about_Intrinsic_Members
- about_Object_Creation
- about_Quoting_Rules
- about_Script_Internationalization
- Import-LocalizedData
- ConvertFrom-StringData
- System.Collections.Hashtable