PowerShell - Getting Started with Dictionaries

by
Jeremy Canfield |
Updated: May 03 2023
| PowerShell articles
Here is how you would create a dictionary that contains a few key value pairs.
$mydict = @{"fruit" = "apple";
"veggy" = "pepper"}
Write-Host Keys = $mydict.Keys
Write-Host Values = $mydict.Values
Which should print the following.
Keys = veggy fruit
Values = pepper apple
Often, you will loop through the dictionary.
$mydict = @{"fruit" = "apple";
"veggy" = "pepper"}
$mydict.GetEnumerator() | ForEach-Object {
Write-Host key = $($_.Key) and value = $($_.Value)
}
Or like this.
$mydict = @{"fruit" = "apple";
"veggy" = "pepper"}
foreach ($element in $mydict.GetEnumerator()) {
Write-Host key = $element.key and value = $element.value
}
Which should now print the following.
key = veggy and value = pepper
key = fruit and value = apple
Did you find this article helpful?
If so, consider buying me a coffee over at