PowerShell: Hashtable: Get Key Value, Add Key, Remove Key
Get a Key's Value
By Index Operator: []
$dict = [ordered] @{"a" = 1; "b" = 2; } $dict["a"] # 1
By Member-Access Operator: .
If key is a string, you can use a property access operator form. 〔see PowerShell: Hashtable Key / Property Name Clash〕
$dict = [ordered] @{"a" = 1; "b" = 2; } $dict.a # 1
Add a Key, or Change a Key's Value
3 ways:
hashtable.add(key,val)
→ functional form. Most precise.hashtable[key] = val
→ operator form.hashtable.key = val
→ property syntax form. Convenient, if no key clash with hashtable member names.
$dict = [ordered] @{"a" = 1; "b" = 2; } $dict.add("c",3) Write-Host $dict # [a, 1] [b, 2] [c, 3]
$dict = [ordered] @{"a" = 1; "b" = 2; } $dict["c"] = 3 Write-Host $dict # [a, 1] [b, 2] [c, 3]
$dict = [ordered] @{"a" = 1; "b" = 2; } $dict.c = 3 Write-Host $dict # [a, 1] [b, 2] [c, 3]
Remove a Key
$dict = [ordered] @{"a" = 1; "b" = 2; } $dict.remove("b") Write-Host $dict # [a, 1]