Checking Whether Hash Table Contains Key

by Sep 9, 2009

In the previous tip, you used a hash table to translate input values. However, unlike Switch-statements, Hash Tables have no "default" so all values need to be present in the hash table. You could check whether a value is present and act accordingly to work around this:

function Get-Name($number) {
$translate = @{
1 = "One"
2 = "Two"
3 = "Three"
}
if ($translate.ContainsKey($number)) {
$translate[$number]
} else {
"Other"
}
}

Get-Name 1
Get-Name 100

Twitter This Tip! ReTweet this Tip!