Hashtable is a very popular data type used to store key and value pairs. As a popular and useful data type, PowerShell supports the HashTable type natively. Hashtable key is used to identify the data and the value is the actual data to use. In this tutorial, we examine how to use the PowerShell hashtable. Programming languages like Python also call the hash table a dictionary.
Define/Declare Hashtable
The hashtable can be created by using curly brackets and separating items with ; sign. Also, the opening curly bracket is prefixed with the @
sign.
$hash_table = @{id=1;name="İsmail";surname="Baydan"}
List Keys
The hashtable provides different attributes which keys
is one of them. The keys attribute can be used to list all keys of the hashtable.
$hash_table = @{id=1;name="İsmail";surname="Baydan"}
$hash_table.keys
id name surname
List Values
Another useful attribute of the hashtable is the values
it simply lists all values in the hashtable.
$hash_table = @{id=1;name="İsmail";surname="Baydan"}
$hash_table.values
1 İsmail Baydan
Access Value with Key
We can access values by specifying their keys. We can get the values by specifying the key. The Key is specified inside square brackets after the hashtable.
$hash_table = @{id=1;name="İsmail";surname="Baydan"}
Write-Host($hash_table["id"])
Write-Host($hash_table["name"])
Write-Host($hash_table["surname"])
1 İsmail Baydan
Update Value
We can update existing values by using its pair. We can use its key and set the new values by using the equal sign.
$hash_table = @{id=1;name="İsmail";surname="Baydan"}
Write-Host($hash_table["id"])
Add New Item (Key/Value)
A new item or key/value pair can be added to the existing hashtable by using the Add()
method. The key is specified as the first parameter and the value is specified as the second parameter.
$hash_table = @{id=1;name="İsmail";surname="Baydan"}
$hash_table.Add("country","Turkey")
Remove Item
We can remove an item from the hashtable by using the Remove()
method and providing the key as the parameter.
$hash_table = @{id=1;name="İsmail";surname="Baydan"}
$hash_table.Remove("id")
Display Item Count
The total item count can be displayed by using the Count
attribute like below.
$hash_table = @{id=1;name="İsmail";surname="Baydan"}
Write-Host($hash_table.Count)