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.
@{ Key1 = 'Value1'; Key2 = 'Value2'; Key3 = 'Value3' }$person = @{ Name = 'Alice'; Age = 30; City = 'Seattle' }$emptyTable = @{}$singleItem = @{ Language = 'PowerShell' }$mixedTypes = @{ Number = 10; IsActive = $true; List = @(1,2,3) }$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'])"@{} to define hash tables, which store key-value pairs.@{}.'Name' = 'Alice' to an existing hash table $person?$person.Add('Name', 'Alice'). Note that the Add() method specifically adds new entries.$hash = @{ 'a' = 1; 'b' = 2 }
$hash['a'] = 3
$hash['c'] = 4
$hash['b']$hash['b'], which was never changed and remains 2.$ht = @{ 'x' = 10 }
$ht.Add('x', 20)$ht is created with key 'x' = 10.$ht.Add('x', 20) tries to add a duplicate key 'x', which causes a runtime error.$users = @('Alice', 'Bob', 'Charlie')
$ages = @(25, 30, 35)Pass the test and this pattern moves unknown