PowerShell Hast table
The PowerShell Hashtable is a data structure that stores one or more key/value pairs. It is also known as the dictionary or an associative array.
In the PowerShell, there exists a Hashtable (System.Collections.Hashtable) object for each hash table.
We can use the properties and methods of the Hashtable object in the PowerShell. The key and the values in the Hash table are also the objects of .NET type.
After the PowerShell version 3.0 introduced, we can use the [ordered] attribute to create an ordered dictionary (System.Collections.Specialized.OrderedDictionary) in PowerShell.
The main difference between the ordered dictionaries and the Hashtable is that the keys in dictionaries always appear in the order in which we list them. But the order of the keys in the Hashtable is not determined.
The following statement is the syntax to create the Hashtable:
The following statement is the syntax to create an ordered dictionary:
Create a Hash Table
The following are the steps to create the hash table in the PowerShell:
- Create a hast table with the @ symbol at the beginning.
- Enclose the hash table in the braces.
- Enter one or more key/value pairs as the content of the hash table.
- To separate each value form it’s key, we must use an equal sign (=).
- To separate the key/value pairs, we must use a semi colon (;) or the line break.
- Those keys which contain the spaces enclosed them in a quotation marks. And the values must be valid expression of PowerShell.
- To manage the Hast table, assign it to the variables.
- When you assign the ordered hast table to the variable, you can place the ordered attribute before @ sign.
If you want to create an empty hash table, type the following command in the PowerShell:
We can also add the keys and values to the hash table when we create it.
The following example describe how to create the hash table with three keys and their values.
Display a Hash table
- To display the hash table, type the name of the variable which stores it. By default, it displays the table with two columns. One column is for the keys and another for their values.
The following command displays the result of hash table:
Name Value ---- ----- Course BCA name Sumit Age 20
- To display all the keys or all the values of the hash table, use the dot (.) notation. The following example displays all the keys of the above example:
Course name Age
The following example displays all the values of the above example:
BCA Sumit 20
- Hash tables have a “count” property, which indicates the total number of key/value pairs in the hash table. The following command will display the total number of key-value pairs in the above example: