Using Powershell 5, I'd like to avoid an hashtable to return $null when a key is not present. Instead, I'd like to trow an exception.
To be clear :
$myht = @{}
$myht.Add("a", 1)
$myht.Add("b", 2)
$myht.Add("c", $null)
$myht["a"] # should return 1
$myht["b"] # should return 2
$myht["c"] # should return $null
$myht["d"] # should throw an exception
a, b, c are ok.
d isn't. It does not detect the missing key and return $null. I expect to throw a exception, because my business case allows $null, but not unknown values.
As a workaround, I try the .Net generic dictionary :
$myht = New-Object "System.Collections.Generic.Dictionary[string, System.Nullable[int]]"
It behaves, however, like the powershell hashtable.
At least, the only alternative I found is to wrap the test in a function:
function Get-DictionaryStrict{
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
[Hashtable]$Hashtable,
[Parameter(Mandatory=$true, Position=1)]
[string]$Key
)
if($Hashtable.ContainsKey($Key)) {
$Hashtable[$Key]
}
else{
throw "Missing value"
}
}
$myht = @{ a = 1; b = 2; c = $null }
Get-DictionaryStrict $myht a
Get-DictionaryStrict $myht b
Get-DictionaryStrict $myht c
Get-DictionaryStrict $myht d
It works the way I want, but the syntax is more verbose, especially when the call to the function takes place within other complex method.
Is there a simpler way ?