Consider the following PowerShell script:
$hash = @{ 'apple' = 3; 'banana' = 5; 'cherry' = 7 }
$result = $hash['banana']
Write-Output $resultWhat will be printed?
$hash = @{ 'apple' = 3; 'banana' = 5; 'cherry' = 7 }
$result = $hash['banana']
Write-Output $resultThink about how to get the value for a key in a hash table.
The hash table stores keys and values. Accessing $hash['banana'] returns the value 5.
Choose the correct PowerShell syntax to create a hash table with keys 'x' and 'y' and values 10 and 20 respectively.
PowerShell uses = to assign values in hash tables, and semicolons separate pairs.
PowerShell hash tables use @{ key = value; key2 = value2 } syntax. Colons are not used.
Look at this script:
$hash = @{ 'a' = 1; 'b' = 2 }
Write-Output $hash[a]Why does it cause an error?
Think about how keys are referenced in PowerShell hash tables.
Hash table keys must be quoted strings when accessed by string keys. Without quotes, PowerShell treats 'a' as a variable.
You have this hash table:
$hash = @{ 'name' = 'Alice'; 'age' = 30 }Which command correctly adds a new key 'city' with value 'Seattle'?
Think about how to assign a new key in a hash table.
Assigning a new key-value pair is done by $hash['key'] = value. The Add() method exists for hashtables but throws an exception if the key already exists.
Consider this script:
$hash = @{ 'one' = 1; 'two' = 2 }
$hash['three'] = 3
$hash['two'] = 22
$hash.Remove('one')How many key-value pairs remain in $hash?
Count how many keys remain after adding, updating, and removing.
Initially 2 keys. Added 'three' (3 keys). Updated 'two' (still 3 keys). Removed 'one' (2 keys remain).