访问哈希表不存在的属性在模块内外的行为不同



在PowerShell脚本或简单的单文件psm1模块中,访问哈希表的不存在属性时返回$null

$hashtable = @{}
$hashtable.NonExistentKey -eq $null # returns true

但是,当该代码是带有psd1清单的适当模块的一部分时,相同的代码会抛出异常

在此对象上找不到属性"NonExistentKey"。请验证该属性是否存在。

也许有人知道这种行为的原因是什么,以及是否可以改变?

UPD:我知道ContainsKey是正确的方法,但它涉及执行遗留代码和不同的行为。

UPD2:设置StrictMode确实如此。谢谢大家!

正如@Jeroen Mostert上面所说,严格模式可能处于活动状态。

具有活动严格模式的PowerShell会话:

> Set-StrictMode -Version 2.0
> $d = @{}
> $d.SomeNotExistingKey
The property 'SomeNotExistingKey' cannot be found on this object. Verify that the property exists.
At line:1 char:1
+ $d.SomeNotExistingKey
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], PropertyNotFoundException
+ FullyQualifiedErrorId : PropertyNotFoundStrict

PowerShell会话无活动严格模式:

> $d = @{}                    
> $d.SomeNotExistingKey      

来自MSDN:

。。。当严格模式打开时,当表达式、脚本或脚本块的内容违反基本最佳实践编码规则时,Windows PowerShell会生成终止错误。

希望这能帮助

最新更新