首页 > 解决方案 > 如果键不存在,如何使哈希表抛出错误?

问题描述

使用 Powershell 5,我想避免$null在密钥不存在时返回哈希表。相反,我想抛出一个例外。

要清楚:

$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没问题。

d不是。它不会检测到丢失的密钥并返回$null。我希望抛出一个异常,因为我的业务案例允许 $null,但不允许未知值。

作为一种解决方法,我尝试使用 .Net 通用字典:

$myht = New-Object "System.Collections.Generic.Dictionary[string, System.Nullable[int]]"

但是,它的行为类似于 powershell 哈希表。

至少,我发现的唯一选择是将测试包装在一个函数中:

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


它按我想要的方式工作,但语法更冗长,特别是当对函数的调用发生在其他复杂方法中时。

有没有更简单的方法?

标签: powershell

解决方案


您可以使用其他集合类型,但也可以使用严格模式

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

你得到一个错误:

在此对象上找不到属性“c”。验证该属性是否存在。

请注意不要破坏工作脚本,因为严格模式会强制执行许多其他内容,而不是不存在属性的错误,例如使用不存在的变量或超出范围的索引时出错。这取决于您在版本中使用的级别。


推荐阅读