0
0
PowerShellscripting~5 mins

Hash tables (dictionaries) in PowerShell

Choose your learning style9 modes available
Introduction
Hash tables help you store and find data quickly using keys, like a real-life dictionary where you look up words to find their meanings.
When you want to store related information with labels, like a contact's name and phone number.
When you need to count how many times something appears, like counting votes or items.
When you want to group data by categories, like organizing books by genre.
When you want to quickly find a value without searching through a list.
When you want to store settings or options with names and values.
Syntax
PowerShell
@{ Key1 = 'Value1'; Key2 = 'Value2'; Key3 = 'Value3' }
Use @{ } to create a hash table in PowerShell.
Keys and values are separated by = and pairs are separated by semicolons.
Examples
Create a hash table with keys Name, Age, and City.
PowerShell
$person = @{ Name = 'Alice'; Age = 30; City = 'Seattle' }
Create an empty hash table with no keys or values.
PowerShell
$emptyTable = @{}
Create a hash table with only one key-value pair.
PowerShell
$singleItem = @{ Language = 'PowerShell' }
Keys can have values of different types like numbers, booleans, or arrays.
PowerShell
$mixedTypes = @{ Number = 10; IsActive = $true; List = @(1,2,3) }
Sample Program
This script creates a hash table of fruits and their colors, shows the contents, adds a new fruit, then shows the updated contents and accesses one value.
PowerShell
$fruitColors = @{ Apple = 'Red'; Banana = 'Yellow'; Grape = 'Purple' }

Write-Host 'Before adding:'
$fruitColors.GetEnumerator() | ForEach-Object { Write-Host "$($_.Key): $($_.Value)" }

# Add a new fruit
$fruitColors['Orange'] = 'Orange'

Write-Host 'After adding Orange:'
$fruitColors.GetEnumerator() | ForEach-Object { Write-Host "$($_.Key): $($_.Value)" }

# Access a value
Write-Host "Color of Banana is: $($fruitColors['Banana'])"
OutputSuccess
Important Notes
Accessing a key that does not exist returns $null without error.
Adding or updating a key is done by assigning a value to that key.
Hash tables provide very fast lookup compared to lists.
Time complexity for lookup, add, or update is generally O(1).
Space complexity depends on the number of key-value pairs stored.
Summary
Hash tables store data as key-value pairs for quick access.
Use @{ } to create hash tables in PowerShell.
You can add, update, and access values using keys easily.