Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a hashtable throw an error if key does not exists?

Tags:

powershell

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 ?

like image 461
Steve B Avatar asked Sep 06 '25 02:09

Steve B


1 Answers

You can use other collection types, but you could also use Strict Mode

Set-StrictMode -Version '2.0'
$x=@{a=5;b=10}
$x.a
$x.c

You get an error:

The property 'c' cannot be found on this object. Verify that the property exists.

Just be careful not to break a working script as Sctrict Mode enforces a bunch of other stuff than error on non-existing property, like error on using non-existing variable or out of bound indexes. It depends on the level you use in Version.

like image 99
AdamL Avatar answered Sep 09 '25 00:09

AdamL