about Hash Tables - PowerShell (2024)

  • 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-Objectcmdlet 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-StringDatacmdlet 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
about Hash Tables - PowerShell (2024)

FAQs

What is all about hash tables PowerShell? ›

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, the ConvertFrom-StringData cmdlet converts structured string data to a hashtable.

What you need to know about hash tables? ›

Hash tables are a type of data structure in which the address/ index value of the data element is generated from a hash function. This enables very fast data access as the index value behaves as a key for the data value.

How to check if value is in HashTable PowerShell? ›

Use the “ContainsKey” method to check if a key exists in a hash table. Consider the size of the hash table and the number of key-value pairs it contains. If you are working with a large amount of data, consider using other data structures like arrays or lists instead.

What is the difference between HashMap and HashTable in PowerShell? ›

HashMap and HashTable are both implementations of a Map - a collection of key value pairs where the keys are unique (kind of like a lookup table). HashTable is thread safe, but HashMap is not. HashTable does not allow a null key, but HashMap does. Differences are based on the different implementations.

Why are hash tables so good? ›

In many situations, hash tables turn out to be on average more efficient than search trees or any other table lookup structure. For this reason, they are widely used in many kinds of computer software, particularly for associative arrays, database indexing, caches, and sets.

What is the difference between array and Hashtable in PowerShell? ›

Generally, you think of a hashtable as a key/value pair, where you provide one key and get one value. PowerShell allows you to provide an array of keys to get multiple values.

How to check hash using PowerShell? ›

If you download the files, what you'd do from PowerShell is run “Get-FileHash” and specify the path to the file you want to be checked. You'll see it generated a hash value of 82F776A89483EB2192FC41637708A820938B9091D5964530A089092CB64AEBFB, and you can compare that to the value on the web page and verify it matches.

How do I check if a Hashtable is empty? ›

The isEmpty method of the Hashtable class is used to check if the specified Hashtable object is empty, i.e., it has no key-value entry present.

How to check Hashtable value? ›

Hashtable. containsValue() method is used to check whether a particular value is being mapped by a single or more than one key in the Hashtable. It takes the Value as a parameter and returns True if that value is mapped by any of the keys in the table.

Which is faster, HashMap or hashtable? ›

HashMap is not synchronized, therefore it's faster and uses less memory than Hashtable. Generally, unsynchronized objects are faster than synchronized ones in a single threaded application.

Can a hashtable have duplicate keys? ›

A Hashtable does not accept duplicate keys. If you add a duplicate key the value will be replaced for that key. Here, you can see that when the key 1 is added again, the value is replaced with Kumaran. So, Hashtable does not accept duplicate keys.

How to convert JSON to hashtable in PowerShell? ›

-AsHashtable. Converts the JSON to a hash table object. This switch was introduced in PowerShell 6.0. Starting with PowerShell 7.3, the object is an OrderedHashtable and preserves the ordering of the keys from the JSON.

How to hash using PowerShell? ›

PowerShell does not provide a cmdlet to compute the hash of a string. However, you can write a string to a stream and use the InputStream parameter of Get-FileHash to get the hash value.

What is the role of hash table? ›

A hash table is a type of data structure in which information is stored in an easy-to-retrieve and efficient manner. In the key-value method, keys are assigned random indexes where their values are stored in an array. The index is the information of where exactly in the array the value is stored.

What is the difference between HashMap and Hashtable? ›

HashMap and HashTable are both key-value storage classes in Java. HashMap is non-synchronized, making it faster for single-threaded tasks, while HashTable is inherently synchronized, providing thread safety. HashTable doesn't allow any null keys or values, but HashMap lets you have one null key and several null values.

What is @{} in PowerShell? ›

25. @{} in PowerShell defines a hashtable, a data structure for mapping unique keys to values (in other languages this data structure is called "dictionary" or "associative array").

Top Articles
Bitcoin wallet - How to set up and create a BTC account
Microsoft Multi-Factor Authentication (MS MFA) - Frequently Asked Questions
Hotels Near 6491 Peachtree Industrial Blvd
Fiskars X27 Kloofbijl - 92 cm | bol
Ffxiv Act Plugin
Craigslist Free En Dallas Tx
Brady Hughes Justified
Inducement Small Bribe
Canary im Test: Ein All-in-One Überwachungssystem? - HouseControllers
Steamy Afternoon With Handsome Fernando
P2P4U Net Soccer
Aiken County government, school officials promote penny tax in North Augusta
Nordstrom Rack Glendale Photos
Palace Pizza Joplin
270 West Michigan residents receive expert driver’s license restoration advice at last major Road to Restoration Clinic of the year
2021 Lexus IS for sale - Richardson, TX - craigslist
The Weather Channel Facebook
Socket Exception Dunkin
OSRS Dryness Calculator - GEGCalculators
Best Suv In 2010
Bitlife Tyrone's
Po Box 35691 Canton Oh
/Www.usps.com/International/Passports.htm
Busted News Bowie County
The Many Faces of the Craigslist Killer
Craigslist Apartments In Philly
Nk 1399
Claio Rotisserie Menu
Carroway Funeral Home Obituaries Lufkin
Login.castlebranch.com
Bridgestone Tire Dealer Near Me
Ezstub Cross Country
Broken Gphone X Tarkov
Wisconsin Volleyball Team Leaked Uncovered
Melissa N. Comics
Flaky Fish Meat Rdr2
7543460065
Chatropolis Call Me
„Wir sind gut positioniert“
Infinite Campus Farmingdale
11526 Lake Ave Cleveland Oh 44102
O'reilly's Palmyra Missouri
814-747-6702
Canvas Elms Umd
Meet Robert Oppenheimer, the destroyer of worlds
UNC Charlotte Admission Requirements
Craigslist Cars For Sale By Owner Memphis Tn
Otter Bustr
Tweedehands camper te koop - camper occasion kopen
Who We Are at Curt Landry Ministries
The Love Life Of Kelsey Asbille: A Comprehensive Guide To Her Relationships
Latest Posts
Article information

Author: Foster Heidenreich CPA

Last Updated:

Views: 5575

Rating: 4.6 / 5 (56 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Foster Heidenreich CPA

Birthday: 1995-01-14

Address: 55021 Usha Garden, North Larisa, DE 19209

Phone: +6812240846623

Job: Corporate Healthcare Strategist

Hobby: Singing, Listening to music, Rafting, LARPing, Gardening, Quilting, Rappelling

Introduction: My name is Foster Heidenreich CPA, I am a delightful, quaint, glorious, quaint, faithful, enchanting, fine person who loves writing and wants to share my knowledge and understanding with you.