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

Dav*_*ard 5 variables powershell 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" }
Run Code Online (Sandbox Code Playgroud)

真假

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

查看变量的类型,我可以看到这$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
Run Code Online (Sandbox Code Playgroud)

检查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" }
Run Code Online (Sandbox Code Playgroud)

True
无法找到类型 [OrderedDictionary]。

Mat*_*sen 4

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

[System.Collections.Specialized.OrderedDictionary]
Run Code Online (Sandbox Code Playgroud)

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

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

  $Dictionary -is [System.Collections.Specialized.OrderedDictionary]
}
Run Code Online (Sandbox Code Playgroud)

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