首页 > 解决方案 > 如何检查 PowerShell 变量是否是有序哈希表?

问题描述

在 PowerShell 中,如何检查变量是否为哈希表,是否已排序?

在第一个例子中,我正在测试一个有序的哈希表是否是 type Hashtable,但似乎不是。

在此之后,我使用 . 检查了变量类型GetType()。这似乎表明有序哈希表是 type OrderedDictionary

最后,我测试了一个有序的哈希表是否是 type 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

但是,当我检查变量是否为 typeOrderedDictionary时,我会收到一条错误消息,指出无法找到该类型。

$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]。

标签: powershellvariableshashtable

解决方案


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

[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


推荐阅读