PowerShell Hashtable

Hashtable in PowerShell



PowerShell Hashtable is a compact data structure that stores key/value pairs in a hash table.
For example, it may contain student’s roll number as key and their name as value.

A key/value pair is essentially a set of two elements that are related in some manner.

How to create Hashtable



Just like array, hashtable can also be created in Multiple ways.
  1. Begin the hash table with an at sign (@).
  2. Enclose the hash table in braces ({}).
It will create an empty hashtable for you. You can add Data in hashtable using add method.


3. You can also add keys and values to a hashtable when you create it. For example, the following statement creates a hash table with three keys.
  • 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 contains spaces must be enclosed in quotation marks. 
  • Strings as values must be in quotation marks, even if they do not include spaces.
If you want to maintain order in which values added in hashtable, use [ordered] attribute before the “@” symbol.



Access values of hashtable



Hashtable value can be accessed using key.


For ordered hashtable value, you can access values just like array using index.

Operations on Hashtable


Display hashtable

Hashtable variable will display keys and values as separate column.


Using Keys and Values properties of hashtable, you can display all keys and values of hashtable.



Add/Remove values

  • One way to add new entry in hashtable is add method which we already discussed.
  • We can also add new entry using below way

  • Remove method can be used to remove entry from hashtable.

Search on hashtable

ContainsKey method search for key and returns true if matches otherwise false.



ContainsValue method search for value and returns true if matches otherwise false.


Sorting on hashtable

Use GetEnumerator method is used to enumerate the keys and values

Sort-Object cmdlet is used to sort the enumerate values.



Looping over hashtable

Foreach loop can be used to iterate over hashtable.


Foreach-Object can also be used to iterate over hashtable




Comments

Popular Posts

How to Import and Export Delimited Files, like CSV, in PowerShell

How to generate a GUID in PowerShell

PowerShell Arithmetic Operators