- 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 Hashtable[System.Collections.Hashtable]
object. You can use the properties and methodsof Hashtable objects in PowerShell.
Beginning in PowerShell 3.0, you can use the [ordered]
attribute to create an[System.Collections.Specialized.OrderedDictionary]
object in PowerShell.
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'tdetermined.
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, PowerShell has a cmdlet,ConvertFrom-StringData
, that converts strings 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.
Creating hashtables
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.
To create an empty hashtable in the value of $hash, type:
$hash = @{}
You can also add keys and values to a hashtable when you create it. Forexample, the following statement creates a hashtable with three keys.
$hash = @{ Number = 1; Shape = "Square"; Color = "Blue"}
Creating ordered dictionaries
You can create an ordered dictionary by adding an object of theOrderedDictionary type, but the easiest way to create an ordered dictionaryis use the [ordered]
attribute.
The [ordered]
attribute is introduced in PowerShell 3.0.
Place the attribute immediately before the "@" symbol.
$hash = [ordered]@{ Number = 1; Shape = "Square"; Color = "Blue"}
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).
You can't use the [ordered]
attribute to convert or cast a hashtable. If youplace the ordered attribute before the variable name, the command fails withthe following error message.
[ordered]$hash = @{}ParserError:Line | 1 | [ordered]$hash = @{} | ~~~~~~~~~~~~~~ | The ordered attribute can be specified only on a hash literal node.
To correct the expression, move the [ordered] attribute.
$hash = [ordered]@{}
You can cast an ordered dictionary to a hashtable, but you can't recover theordered attribute, even if you clear the variable and enter new values. Tore-establish the order, you must remove and recreate the variable.
[hashtable]$hash = [ordered]@{ Number = 1; Shape = "Square"; Color = "Blue"}$hash
Name Value---- -----Color BlueShape SquareNumber 1
Displaying hashtables
To display a hashtable that's saved in a variable, type the variable name. Bydefault, a hashtables is displayed as a table with one column for keys and onefor values.
$hash
Name Value---- -----Shape SquareColor BlueNumber 1
hashtables have Keys and Values properties. Use dot notation to displayall the keys or all the values.
$hash.keys
NumberShapeColor
$hash.values
1SquareBlue
Each key name is also a property of the hashtable, and its value is the valueof the key name property. Use the following format to display the propertyvalues.
$hashtable.<key><value>
For example:
$hash.Number1$hash.ColorBlue
hashtables have a Count property that indicates the number of key-valuepairs in the hashtable.
$hash.count3
hashtable tables aren't arrays, so you can't use an integer as an indexinto the hashtable, but you can use a key name to index into the hashtable.If the key is a string value, enclose the key name in quotation marks.
For example:
$hash["Number"]1
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 applies for other types which 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 anordered dictionary to ensure the output isalways in the same order. These examples work the same for normal hashtables,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
To add keys and values to a hashtable, use the following command format.
$hash["<key>"] = "<value>"
For example, to add a "Time" key with a value of "Now" to the hashtable, usethe following statement format.
$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. The Removemethod takes the key as its value.
The Remove
method has the following syntax:
Remove(Key)
For example, to remove the Time=Now
key-value pair from the hashtable in thevalue of the $hash
variable, type:
$hash.Remove("Time")
You can use all of the properties and methods of Hashtable objects inPowerShell, including Contains
, Clear
, Clone
, and CopyTo
. For moreinformation about Hashtable objects, seeSystem.Collections.Hashtable.
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 method ofhashtables 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