ABOUT_HASH_TABLES 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 data structure that stores one or more key-value pairs. For example, a hash table might contain a series of IP addresses and computer names, where the IP addresses 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 methods of 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 in the order in which you list them. The order of keys in a hashtable isn't determined. The keys and value in hashtables are also .NET objects. They're most often strings or integers, but they can have any object type. You can also create nested hashtables, in which the value of a key is another hashtable. Hashtables are frequently used because they're efficient for finding and retrieving data. You can use hashtables to store lists and to create calculated properties in PowerShell. And, PowerShell has a cmdlet, ConvertFrom-StringData, that converts strings to a hashtable. Syntax The syntax of a hashtable is as follows: @{ = ; [ = ] ...} The syntax of an ordered dictionary is as follows: [ordered]@{ = ; [ = ] ...} 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 be valid PowerShell expressions. Strings must appear in quotation marks, even if they don't include spaces. - To manage the hashtable, save it in a variable. - When assigning an ordered hashtable to a variable, place the [ordered] type before the @ symbol. If you place it before the variable name, the command fails. 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. For example, 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 the ORDEREDDICTIONARY type, but the easiest way to create an ordered dictionary is 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 or dictionary (IDICTIONARY). You can't use the [ordered] attribute to convert or cast a hashtable. If you place the ordered attribute before the variable name, the command fails with the following error message. [ordered]$hash = @{} At line:1 char:1 + [ordered]$hash = @{} + ~~~~~~~~~~~~~~ The ordered attribute can be specified only on a hash literal node. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : OrderedAttributeOnlyOnHashLiteralNode To correct the expression, move the [ordered] attribute. $hash = [ordered]@{} You can cast an ordered dictionary to a hashtable, but you can't recover the ordered attribute, even if you clear the variable and enter new values. To re-establish the order, you must remove and recreate the variable. [hashtable]$hash = [ordered]@{ Number = 1; Shape = "Square"; Color = "Blue"} $hash Name Value ---- ----- Color Blue Shape Square Number 1 Displaying hashtables To display a hashtable that's saved in a variable, type the variable name. By default, a hashtables is displayed as a table with one column for keys and one for values. $hash Name Value ---- ----- Shape Square Color Blue Number 1 hashtables have KEYS and VALUES properties. Use dot notation to display all the keys or all the values. $hash.keys Number Shape Color $hash.values 1 Square Blue Each key name is also a property of the hashtable, and its value is the value of the key name property. Use the following format to display the property values. $hashtable. For example: $hash.Number 1 $hash.Color Blue hashtables have a COUNT property that indicates the number of key-value pairs in the hashtable. $hash.count 3 hashtable tables aren't arrays, so you can't use an integer as an index into 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 HASHTABLE type, you can use the PSBASE intrinsic member to access those properties. For example, if the key name is keys and you want to return the collection of the HASHTABLE keys, use this syntax: $hashtable.psbase.Keys This applies for other types which implement the SYSTEM.COLLECTIONS.IDICTIONARY interface, like ORDEREDDICTIONARY. Iterating over keys and values You can iterate over the keys in a hashtable to process the values in several ways. Each of the examples in this section has identical output. They iterate over 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 the output is always 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: 1 The value of 'Shape' is: Square The 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 pair through 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 over each 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[""] = "" For example, to add a "Time" key with a value of "Now" to the hashtable, use the following statement format. $hash["Time"] = "Now" You can also add keys and values to a hashtable using the Add method of the SYSTEM.COLLECTIONS.HASHTABLE object. The Add method has the following syntax: Add(Key, Value) For example, to add a Time key with a value of Now to the hashtable, use the 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 following statement 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 hash table, but you can use the Remove method of the Hashtable object. The Remove method 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 the value of the $hash variable, type: $hash.Remove("Time") You can use all of the properties and methods of Hashtable objects in PowerShell, including Contains, Clear, Clone, and CopyTo. For more information about Hashtable objects, see System.Collections.Hashtable. Object Types in HashTables The keys and values in a hashtable can have any .NET object type, and a single hashtable can have keys and values of multiple types. The following statement creates a hashtable of process name strings and process object 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 to display the values. PS> $p Name Value ---- ----- PowerShell System.Diagnostics.Process (PowerShell) Notepad System.Diagnostics.Process (notepad) PS> $p.PowerShell Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 441 24 54196 54012 571 5.10 1788 PowerShell PS> $p.keys | ForEach-Object {$p.$_.handles} 441 251 The keys in a hashtable can be any .NET type. The following statement adds a key-value pair to the hashtable in the $p variable. The key is a SERVICE object that represents the WinRM service, and the value is the current status of 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 that you use for other pairs in the hashtable. PS> $p Name Value ---- ----- PowerShell System.Diagnostics.Process (powershell) Notepad System.Diagnostics.Process (Notepad) WinRM Running PS> $p.keys PowerShell Notepad Status 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 following statement adds key-value pair to the hashtable in the $p variable in which the key is a string, Hash2, and the value is a hashtable with three key-value pairs. $p = $p + @{ "Hash2"= @{a=1; b=2; c=3} } You can display and access the new values using the same methods. PS> $p Name Value ---- ----- PowerShell System.Diagnostics.Process (powershell) Notepad System.Diagnostics.Process (Notepad) WinRM Running Hash2 {c, b, a} PS> $p.Hash2 Name Value ---- ----- c 3 b 2 a 1 PS> $p.Hash2.b 2 Sorting Keys and Values The items in a hashtable are intrinsically unordered. The key-value pairs might appear in a different order each time that you display them. Although you can't sort a hashtable, you can use the GetEnumerator method of 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 hash table in the $p variable and then sort the keys in alphabetical order. PS> $p.GetEnumerator() | Sort-Object -Property key Name Value ---- ----- Hash2 {c, b, a} Notepad System.Diagnostics.Process (Notepad) PowerShell System.Diagnostics.Process (powershell) WinRM Running The following command uses the same procedure to sort the hash values in descending order. PS> $p.GetEnumerator() | Sort-Object -Property Value -Descending Name Value ---- ----- PowerShell System.Diagnostics.Process (powershell) Notepad System.Diagnostics.Process (Notepad) Hash2 {c, b, a} WinRM Running Creating Objects from hashtables Beginning in PowerShell 3.0, you can create an object from a hashtable of properties and property values. The syntax is as follows: []@{ = = } This method works only for classes that have a constructor that has no parameters. 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 of key-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 the Import-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 include quotation marks. For more information about here-strings, see about_Quoting_Rules. The following example shows how to create a here-string of the user messages in the previous example and how to use ConvertFrom-StringData to convert them from a string into a hashtable. The following command creates a here-string of the key-value pairs and then saves 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 the here-string into a hashtable. ConvertFrom-StringData $string Name Value ---- ----- Msg3 Enter an alias (or "nickname"). Msg2 She said, "Hello, World." Msg1 Type "Windows". For more information about here-strings, see about_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