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.
- Begin the hash table with an at sign (@).
- Enclose the hash table in braces ({}).
- 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.
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
Post a Comment