PowerShell programming offers hashtables to store key and value pairs, also known as associative arrays.

Keys are strings, and values can contain any type of data.

Keys are of strings, and values contains any type of data.

Hashtable variables are declared as follows:

 $dictionry = @{} # Empty Hashtable

To initialize a hashtable with sample data

 $dictionry = @{
  "key":"value",
  "key1":"value1"
 } # Hashtable key and values

Example of key-value pairs in a hashtable.

$employee = @{
    id = 1
    name = "Eric"
    salary = 5000
}

How to access key-value pairs in powershell

Values can be retrieved using the key of a hashtable.

Syntax:

$($hashtable["key"])

If the key is found, it returns the value; otherwise, it returns empty.

Write-Host "$($employee["id"])" # Return 1
Write-Host "$($employee["name"])" # Return Eric

How to update key-value pairs

Key-value pairs are added using the following syntax:

$hashtable[key]=value

If the key is found, the current value is updated with the new value. If the key is not found, the key-value pair is added to the hashtable.

$employee["id"]= 11
$employee["name"]= "John"
$employee["dept"]= "sales"

Write-Host "$($employee["id"])" # Updates and return 11,
Write-Host "$($employee["name"])" # Updates and return John
Write-Host "$($employee["dept"])" # adds pairs and return sales
Write-Host "$($employee["roles"])" ## Key not found, return empty

Iterate through hashtable

By default, if you print a hashtable variable using Write-Host "$employee", it prints the class name System.Collections.Hashtable, not the data inside it. This is not helpful for debugging.

Use a foreach loop to iterate through the hashtable:

foreach ($key in $employee.Keys) {
    $value = $employee[$key]
    Write-Host "$key - $value"
}

Remove key-value pair

To remove an element from a hashtable, use the Remove method:

$hashtable.remove(key)

If the key is found, it removes the key-value pair; if not found, it returns empty.

$employee.remove("id")
$employee.remove("name1")

Write-Host "$($employee["id"])" # return empty

Check if key exists in hashtable

Sometimes, we need to check if a key exists in a hashtable or not.

To check if a key exists or not, use the ContainsKey method and pass the key ID.

$hashtable.ContainsKey(key)

If the key is found, it returns True; otherwise, it returns False.

Use conditional if statements to check keys and write conditional code blocks.

$employee = @{
    id = 1
    name = "Eric"
    salary = 5000
}
# check key exists
if ($employee.ContainsKey('id')) {
    Write-Host "id found "
} else {
    Write-Host "id not found"
}


# check key not exists
if ($employee.ContainsKey('abcdef')) {
    Write-Host "abcdef found "
} else {
    Write-Host "abcdef not found"
}