Powershell 如果键不存在,如何使哈希表抛出错误?
使用Powershell 5,我希望避免在密钥不存在时使用哈希表返回Powershell 如果键不存在,如何使哈希表抛出错误?,powershell,Powershell,使用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
$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
它按照我想要的方式工作,但语法更为详细,尤其是在其他复杂方法中调用函数时
有更简单的方法吗?使用字典
类型:
$dict = [System.Collections.Generic.Dictionary[string,object]]::new()
$dict.Add('a',$something)
$dict.Add('b',$null)
$dict.Item('a') # returns value of `$something`
$dict.Item('b') # returns `$null`
$dict.Item('c') # throws
您可以使用其他集合类型,但也可以使用 您将得到一个错误: 在此对象上找不到属性“c”。验证 财产存在
只是要小心不要破坏一个工作脚本,因为Sctrict模式在不存在的属性上强制执行一系列错误以外的其他内容,例如使用不存在的变量或越界索引时出错。这取决于您在版本中使用的级别 为什么不直接使用
.ContainsKey()
方法呢?它的存在正是为了您所描述的目的。使用Item
方法也是解决方案的一部分,使用泛型本身是不够的。不管怎样,它是有效的!我学到了一些东西,我不知道我们可以调用键作为obj属性(比如javascript)。谢谢你。不幸的是,strict模式导致了其他复杂性,因此它不适用于我的情况。
Set-StrictMode -Version '2.0'
$x=@{a=5;b=10}
$x.a
$x.c