如何检查PowerShell变量是否为有序哈希表?

5
在PowerShell中,如何检查一个变量是否为哈希表(无论是否有序)?
在第一种情况下,我正在测试有序哈希表是否为Hashtable类型,但它似乎不是。
随后,我使用GetType()检查变量类型。这似乎表明有序哈希表的类型为OrderedDictionary
最后,我尝试测试有序哈希表是否为OrderedDictionary类型,但结果出现错误。
我认为一定有方法来实现这个功能。
检查仅是否为Hashtable
$standard = @{}
$ordered = [ordered]@{}

if ($standard -is [Hashtable]) { Write-Output "True" } else { Write-Output "False" }
if ($ordered -is [Hashtable]) { Write-Output "True" } else { Write-Output "False" }


获取普通和有序哈希表的变量类型

查看变量类型,我发现$ordered似乎是一种名为OrderedDictionary的不同类型。

$standard = @{}
$ordered = [ordered]@{}

Write-Output $standard.GetType()
Write-Output $ordered.GetType()



IsPublic IsSerial Name              BaseType  
-------- -------- ----              --------  
True     True     Hashtable         System.Object  
True     True     OrderedDictionary System.Object

检查 HashtableOrderedDictionary

但是,当我检查一个变量是否为 OrderedDictionary 类型时,会提示找不到该类型的错误。

$standard = @{}
$ordered = [ordered]@{}

if (($standard -is [Hashtable]) -or ($standard -is [OrderedDictionary])) { Write-Output "True" } else { Write-Output "False" }
if (($ordered -is [Hashtable]) -or ($ordered -is [OrderedDictionary])) { Write-Output "True" } else { Write-Output "False" }

True
无法找到类型 [OrderedDictionary]。


4
你需要明确表示:[System.Collections.Specialized.OrderedDictionary]。如果你只输入[OrderedDictionary]并在括号内按Tab键,PowerShell控制台会为你提供自动完成功能。由于System是可选的,因此你可以稍微缩短为[Collections.Specialized.OrderedDictionary],但不能再更短。(至少我不知道还有什么更短的方式;Hashtable似乎会得到特殊处理。) - Jeroen Mostert
4
顺便提一下,与其明确测试这两种具体类型中的任何一个,最好测试 -is [System.Collections.IDictionary],因为它可以包含这两个类型以及你可以以相同方式访问的任何其他类型。 - Jeroen Mostert
2
@JeroenMostert,非常感谢,那个方法很有效。我还发现,如果我在脚本顶部添加using namespace System.Collections.Specialized,我确实可以将其使用缩短为[OrderedDictionary] - David Gard
在PowerShell 5中添加了using namespace。太好了,我不知道这个功能。 :-) - Jeroen Mostert
每次我对类有疑问时,我都会使用 get-Member。 - JPBlanc
3个回答

4

正如评论中所指出的,完整的命名空间限定类型名称为:

[System.Collections.Specialized.OrderedDictionary]

如果您想要接受两种类型的参数,例如作为函数参数,可以使用它们的公共接口IDictionary
function Test-IsOrdered
{
  param(
    [System.Collections.IDictionary]
    $Dictionary
  )

  $Dictionary -is [System.Collections.Specialized.OrderedDictionary]
}

Test-IsOrdered现在可以接受任何类型的字典,包括常规的[hashtable]Test-IsOrdered @{},但只有Test-IsOrdered ([ordered]@{})才会返回$true


2

如上评论所述,您可以检查System.Collections.IDictionary接口,这个接口被两个类实现,用于检查变量是否为哈希表:


> $standard -is [System.Collections.IDictionary]
True
> $ordered -is [System.Collections.IDictionary]
True
< p > OrderedDictionary 定义在 System.Collections.Specialized 中,因此您需要检查以下内容:


> $ordered -is [System.Collections.Specialized.OrderedDictionary]
True
> $standard -is [System.Collections.Specialized.OrderedDictionary]
False

1

他使用Get-Member命令获取最终类型。

($ordered | Get-Member)[0].TypeName

提供: System.Collections.Specialized.OrderedDictionary


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接