PowerShell Hash tables or dictionaries are used to store the data in (key, value) pairs. Hash tables are very useful to retrieve the data. As it maintains, (key, value) pairs; the data structure supports fast access to find or retrieve the data.
We can also call Hash tables as associative Arrays.
Creating Hash tables
As mentioned above, Hash tables are (key, value) pairs. To create the Hash tables, we must pass the key and value details; key and value should be separated using equal (=) sign; and these pairs are separated using commas (;) enclosed in curly braces ({}), prefixed with a symbol (@).
Here is an example to create a hash table;
$categories= @{1 = "Cars"; 2 = "Bikes"; 3 = "Trucks"}
Keys can be numbers or strings or any other supported data types. Key or Name and Value should be separated by using equal (=) sign.
We can also create empty Hash tables; those do not have (key, value) pairs. Below is an example;
$empty_hash = @{}
Accessing data from Hash tables
Hash tables holds the data in (key, value) pairs. To access the values from Hash tables; you must have to access them through the keys.
Either you can use index operator ([]) or a dot (.) operator to pass the key; to retrieve it’s associated value. Here are some examples;
@categories.1
OR
@categories[1]
You will see the value “One” is returned from above statements. PowerShell doesn’t show any Error, if you attempt to retrieve the value of non existing key. It simply, doesn’t return anything.
How do we know the entries in the Hash table?
If you type the variable name of the Hash table; it will display the content. For example, below statement displays all the keys and associated values in the structured way.
PS C:\> $categories Name Value ---- ----- 3 Trucks 2 Bikes 1 Cars
Each Hash table has; Keys or Names and associated Values. By using keys
and values
members of the Hash table, we can access the list of Names or Keys and associated Values.
Display Keys
PS C:\> $categories.keys 3 2 1
Display Values
PS C:\> $categories.values Trucks Bikes Cars
Adding and Removing entries in Hash tables
So far, we have discussed creating and accessing elements in Hash table. We can also add entries to Hash tables and removing them whenever the entries are not required in Hash tables.
To add an entry, you must first give the key to which the value has to be associated. If the key already exists, it replaces the value; otherwise, it adds the (key, value) entry to the Hash table. Below is an example to add an entry to the Hash table;
$categories.4 = "Four"
OR
$categories[4] = "Four"
You can also add entries to Hash table using it’s Add
method. Below is a simple example;
$categories.Add(5, "Five")
To remove the entries in Hash table; use Remove
method of it. You need to pass the key as an argument. Below statement removes the key 4 and it’s associated value;
$categories.remove(4)
[..] David