EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PowerShell Tutorial Hashtable in PowerShell
Secondary Sidebar
PowerShell Tutorial
  • Variables
    • PowerShell Variables
    • PowerShell Environment Variables
    • PowerShell set environment variable
    • Hashtable in PowerShell
    • Set Variable in PowerShell
  • Basics
    • PowerShell Restart Service
    • PowerShell comment
    • PowerShell Map Network Drive
    • PowerShell Append to File
    • PowerShell print
    • What is PowerShell
    • Uses Of Powershell
    • PowerShell Empire
    • PowerShell Parameter
    • PowerShell Stop Service
    • PowerShell Versions
    • How To Install PowerShell
    • PowerShell uninstall module
    • How to Use PowerShell?
    • PowerShell Logging
    • PowerShell Tools
    • PowerShell Commands
    • PowerShell Version Command
    • PowerShell Administrator
    • PowerShell Modules
    • PowerShell Registry
    • PowerShell block Comment
    • PowerShell Verbs
    • PowerShell list
    • PowerShell add user to group
    • PowerShell Write to Console
    • Variable in PowerShell
    • PowerShell New Line
    • PowerShell prompt for input
    • PowerShell File Extension
    • Powershell Remotesigned
    • PowerShell Write to File
    • PowerShell Ping
    • PowerShell wget
    • PowerShell Global variable
    • PowerShell Get-ADGroup
    • Array in PowerShell
    • PowerShell Multidimensional Array
    • PowerShell Array of Strings
    • PowerShell? join array
    • Useful PowerShell Scripts
    • String in PowerShell
    • PowerShell Switch Statement
    • PowerShell Function Parameters
    • PowerShell vs PowerShell ISE
    • PowerShell test-connection
    • PowerShell Test-NetConnection
    • PowerShell GUI
    • PowerShell Variable in String
    • PowerShell Active Directory
  • Operators
    • PowerShell Operators
    • Comparison Operators in PowerShell
    • Logical Operators in PowerShell
    • PowerShell Boolean
    • PowerShell Like Operator
  • cmdlet
    • PowerShell Wait
    • PowerShell Match
    • cmdlets in PowerShell
    • Start PowerShell from cmd
    • Add-Content in PowerShell
    • Get Help in PowerShell
    • PowerShell Copy-Item
    • PowerShell Remove-Item
    • PowerShell Move-Item
    • Get Command in PowerShell
    • PowerShell Run Command
    • Windows PowerShell ISE
    • Windows Powershell Commands
    • WinRM PowerShell
    • PowerShell Date
    • Powershell Write-Host
    • PowerShell Get-ChildItem
    • PowerShell Sort-Object
    • PowerShell Where Object
    • PowerShell Set-Content
    • PowerShell Set-Location
    • PowerShell Invoke-Command
    • PowerShell Invoke-Webrequest
    • PowerShell Get-Location
    • PowerShell Get-Date
    • PowerShell Get-Service
    • PowerShell Test-Path
    • Powershell Module Path
    • PowerShell Out-File
    • PowerShell if File Exists
    • Powershell Copy File
    • PowerShell Delete File
    • PowerShell New-Item
    • PowerShell Rename-Item
    • PowerShell ComputerName
    • PowerShell Get-Content
    • PowerShell Get-Item
    • PowerShell Get-ADUser
    • PowerShell Grep
    • PowerShell Concatenate String
    • PowerShell Get-Process
    • PowerShell Count
    • PowerShell pause
  • Control Statements
    • If Statement in PowerShell
    • If Else in PowerShell
    • Else If in PowerShell
    • Loops in PowerShell
    • For loop in PowerShell
    • PowerShell While Loop
    • PowerShell do while
    • PowerShell Loop through Array
    • PowerShell add to array
    • PowerShell ForEach Loop
    • PowerShell Break
    • PowerShell Continue
    • Switch Case in PowerShell
    • PowerShell If-Not
    • Try-catch in PowerShell
  • Functions
    • PowerShell Functions
    • PowerShell String Functions
    • powershell nslookup
    • PowerShell here string
    • PowerShell Wildcards
    • Regex in PowerShell
    • PowerShell not like
    • PowerShell Filter
    • PowerShell Sleep
    • PowerShell where
    • PowerShell join string
    • PowerShell Exit
    • PowerShell null
    • PowerShell Dictionary
    • PowerShell Location
    • PowerShell Start-Service
    • PowerShell is not digitally signed
    • PowerShell Uptime
    • PowerShell Create Directory
    • PowerShell Trim
    • PowerShell Join-Path
    • PowerShell Execution Policy
    • PowerShell SubString
    • PowerShell Format Table
    • PowerShell Import Module
    • PowerShell ForEach Object
    • PowerShell Alias
    • PowerShell Scheduled Task
    • PowerShell Convert String to Date
    • PowerShell Split String
    • PowerShell Multiline String
    • PowerShell MultiLine Comment
    • PowerShell Rename Folder
    • PowerShell Delete Folder
    • PowerShell String Replace
    • PowerShell join
    • PowerShell xcopy
    • PowerShell Base64
    • PowerShell Tail
    • PowerShell User List
    • PowerShell remove User from group
    • PowerShell JSON Format
    • PowerShell Send Mail
    • PowerShell Convert to String
    • PowerShell Start-Process
    • PowerShell change directory
    • PowerShell Open File
    • PowerShell Batch File
    • PowerShell ZIP
    • PowerShell unzip
    • PowerShell XML
    • PowerShell XML Parsing
    • Remote PowerShell
    • PowerShell Escape Character
    • PowerShell scriptblock
    • PowerShell Executable Location
    • PowerShell Import-CSV?
    • PowerShell Export CSV
  • Interview Questions
    • PowerShell Interview Questions

Related Courses

Shell Scripting Course

All in One Data Science Courses

Data Visualization Courses

Hashtable in PowerShell

By Priya PedamkarPriya Pedamkar

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.

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:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

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 )

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,471 ratings)

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
Popular Course in this category
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)
  41 Online Courses |  13 Hands-on Projects |  322+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Shell Scripting Training (4 Courses, 1 Project)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
Data Visualization Training (15 Courses, 5+ Projects)4.7
1 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

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

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

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

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

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

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

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

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more