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

How do you check if a PowerShell variable is an ordered hashtable?

在 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" }

True
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
Unable to find type [OrderedDictionary].

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

[System.Collections.Specialized.OrderedDictionary]

如果您想接受两种类型,例如作为函数中的参数参数,请使用它们的通用接口IDictionary:

function Test-IsOrdered
{
  param(
    [System.Collections.IDictionary]
    $Dictionary
  )

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

Test-IsOrdered 现在将接受 any 字典类型,包括常规 [hashtable]: Test-IsOrdered @{},但只有 Test-IsOrdered ([ordered]@{}) 会 return $true

如上述评论所述,您可以检查由 类 实现的 System.Collections.IDictionary 接口,以检查变量是否为一般哈希表:

> $standard -is [System.Collections.IDictionary]
True
> $ordered -is [System.Collections.IDictionary]
True

OrderedDictionary 是在 System.Collections.Specialized 中定义的,因此您必须检查:

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

我将使用 Get-Member 来获得最终类型。

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

给出:System.Collections.Specialized.OrderedDictionary