EDUCBA Logo

EDUCBA

MENUMENU
  • Explore
    • EDUCBA Pro
    • PRO Bundles
    • Featured Skills
    • New & Trending
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign Up
Home Data Science Data Science Tutorials PowerShell Tutorial Hashtable in PowerShell
 

Hashtable in PowerShell

Priya Pedamkar
Article byPriya Pedamkar

Updated March 23, 2023

Hashtable in PowerShell

 

 

Introduction to Hashtable in PowerShell

PowerShell Hashtable is a compact data structure that stores key/value pairs in a hash table. In other words, a hashtable is an associative array or a dictionary with a key-value pair. A key/value pair is essentially a set of two elements that are related in some manner.

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

In a hashtable, the input is a unique key with an associated value and output is a table with two columns.

  • Name
  • Value

In PowerShell, each hashtable is a Hashtable object. This object is mostly a string or an integer, but it can be any object type.

Syntax:

Before using a hashtable, it must be created. Below is the syntax for doing so.

Creating an empty hashtable

$hash =@{}

You can also create a hashtable and add keys-values at the same time.

$hash = @{ key1 = item1; key2 = item2;... }

To an empty hashtable, data can be added in the following manner:

$hash.add( $key, $value )

An ordered dictionary can also be created using similar syntax.

Following is the syntax for creating an ordered dictionary. Here, we have only added  [ordered] attribute before the “@” symbol.

$hash =[ordered] @{ key1 = item1; key2 = item2;... }

Note: The main difference between a hashtable and an ordered dictionary is that hashtable does not maintain the order in which entries are added but ordered dictionary does.

Accessing hashtable values: A hashtable value is accessed through the key.

$hash[“key1”]

Printing hashtable: To print /display a hashtable, just type the variable name in which hashtable is saved.

$hash

The above command displays a table with two columns, one for keys and the other one for the associated values for the keys.

How does Hashtable work in PowerShell?

  • Hashtable transforms the key using a hash function into a hash.
  • Hash is a number that the hash table uses to get the value.
  • Hash then maps directly to a bucket in the array of key/value pairs.

Let’s understand the working of PowerShell through given examples:

  • First, create an empty hashtable and then populate it with the key-value pairs or,

Code:

$hash = @{}
$hash.add( 'ID', 1 )
$hash.add( 'Subject', 'Maths')
$hash.add( 'Maths', 80 )
$hash

Output:

Hashtable in PowerShell output 1

  • You can also create a hashtable and initialize it at the same time.

Code:

$hash = @{ID=1; Subject='Maths'; Marks=80}
$hash

Output:

Hashtable in PowerShell output 2

For an ordered hashtable

Code:

$hash=[ordered]@{ID=1; Subject='Maths'; Marks=80}
$hash

Output:

Hashtable in PowerShell output 3

Shown here are few examples to illustrate the actions which can be performed on a hashtable.

Editing items in a hashtable

.Set_Item() method is used to edit the items in a hashtable:

Code:

$hash=[ordered]@{ID=1; Subject='Maths'; Marks=80}
$hash.Set_Item("Subject", “English”)
$hash

Output:

Hashtable in PowerShell output 4

  • A new entry gets automatically added to the hashtable if it did not exist earlier.

Code:

$hash=[ordered]@{ID=1; Subject='English'; Marks=80}
$hash.Set_Item("NoOfStudents",30)
$hash

Output:

Hashtable in PowerShell output 5

Removing items from a hashtable

Code:

$hash=[ordered]@{ID=1; Subject='English'; Marks=80}
$hash.Remove("NoOfStudents")
$hash

Output:

Hashtable in PowerShell output 6

Printing the hashtable keys

 Code:

$hash=[ordered]@{ID=1; Subject='English'; Marks=80}
$hash.keys

Output:

Hashtable in PowerShell output 7

Printing the hashtable values

Code:

$hash=[ordered]@{ID=1; Subject='English'; Marks=80}
$hash.values

Output:

Hashtable in PowerShell output 8

Searching for specific items

Code:

$hash=[ordered]@{ID=1; Subject='Maths'; Marks=80}
If ($hash.Subject -eq ‘Maths’) {Echo ‘OK’}

Output:

output 9

Here, if the “Subject” key-value matches with ‘Maths’, the output is ‘OK’.

For partial matches, .ContainsKey or .ContainsValue methods are used.

$hash.ContainsKey(‘Subject’)

This will return True as output since Key matches with ‘Subject’.

$hash.ContainsKey('Date')

This will return False as output since Key does not match with ‘Date’.

$hash.ContainsValue(‘Maths’)

This will return True as output since Value matches with ‘Maths’.

$hash.ContainsValue('Physics')

This will return False as output since Value does not match with ‘Physics’.

You can also check if the particular key exists or not.

Code:

$hash=[ordered]@{ID=1; Subject='Maths'; Marks=80}
If ($hash.Subject) {Echo ‘OK’}

Output:

output 10

Sorting Keys and Values

  • Hashtable entries are unsorted by default.
  • Each time you print the key/value, the order might appear different.
  • Since it is always convenient to work with the sorted list of data, you can sort the hashtable key/value pairs in Powershell, though you can not sort the hashtable itself.
  • GetEnumerator method is used to enumerate the keys and values
  • Then, Sort-Object cmdlet is used to sort the enumerate values for printing.

Let us understand this through an example.

Code:

$hash.GetEnumerator() | Sort-Object -Property key

Output:

output 11

In the above example first, the keys and values in the hashtable are enumerated In the $hash variable and then keys are sorted in alphabetical order.

  • To sort the hashtable values in descending order, let us see the below example. It is done a similar way as above, only you need to add “Descending” in the cmdlet.

Code:

$hash=[ordered]@{ID=1; Subject='Maths';Marks=80}
$hash.GetEnumerator() | Sort-Object -Property key -Descending

Output:

output 12

Splatting Through a Hashtable

  • Method of supplying parameters to a command as a unit using a dictionary or a list.
  • It is helpful in cases when you need to specify a lot of parameters which makes your command lengthy and you end up scrolling off the screen or try wrapping it up to make it readable.
  • With splatting, instead of providing all the parameters in one line stretching all across the screen, you can use an array or a hashtable which is much easier to read.
  • Splatting makes code reading easier by providing a clean and concise format Let us understand this through a very simple example.

Code:

$splat= @{year = 2019; Month = 12; day=1}
get-date @splat

Output:

output 13

Note:$sign in variable name $splat becomes an @sign while executing the command

Use of @sign instead of $sign invokes the splat operation.

Looping through a Hashtable

Let us with the help of the below example:

1. Using ForEach

Code:

$hash=[ordered]@{ID=1; Subject='Maths';Marks=80}
foreach
($key in $hash.keys)
{
$message = '{0} is {1}' -f $key, $hash[$key] Write-Output $message
}

Output:

output 14

Here, we are moving through each key in the hashtable and accessing the

value using it

2. Using ForEach-Object

Code:

Hashtable in PowerShell code 1

Output:

output 15

3. Unwrapping the hashtable object with GetEnumerator()

Code:

Hashtable in PowerShell code 2

Output:

output 16

Here, each key-value pair passes through the pipeline. The main purpose of using the GetEnumerator() method is to unwrap the PowerShell object into its individual elements.

Conclusion – Hashtable in PowerShell

In this article, we touched upon some important aspects of a hashtable in Powershell.

To summarize:

  • Hashtable is a lightweight data structure used as an associative array to map keys to values.
  • It is a structured and effective way of finding and retrieving data.
  • Can store lists.
  • Can create calculated properties in PowerShell.

Recommended Article

This is a guide to Hashtable in PowerShell. Here we discuss How does Hashtable work in PowerShell along with the Sorting Keys and Values. You may also look at the following article to learn more –

  1. PowerShell Remove-Item
  2. Comparison Operators in PowerShell
  3. Array in PowerShell
  4. PowerShell Variables
  5. Examples to Implement PowerShell Get-Date
  6. Guide to Unique Key in SQL

Primary Sidebar

Footer

Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

© 2025 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA Login

Forgot Password?

🚀 Limited Time Offer! - 🎁 ENROLL NOW