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

标签 powershell variables 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]

如果您想同时接受这两种类型,例如作为函数中的参数参数,请使用它们的通用接口(interface) IDictionary :
function Test-IsOrdered
{
  param(
    [System.Collections.IDictionary]
    $Dictionary
  )

  $Dictionary -is [System.Collections.Specialized.OrderedDictionary]
}
Test-IsOrdered现在将接受任何字典类型,包括常规 [hashtable] : Test-IsOrdered @{} , 但仅限 Test-IsOrdered ([ordered]@{})将返回 $true

关于powershell - 如何检查 PowerShell 变量是否是有序哈希表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57181091/

相关文章:

sql - 如何格式化 SQLCMD 输出

powershell 获取文件的第一个 x MB

excel - 使用单元格的值作为宏的一部分

variables - 批处理脚本日期到变量中

c - c中不同源文件之间的共享变量

azure - ARM模板: how to read output result in array format

powershell - %{ $_.Key1 } 是什么意思?

c# - 从 HashTable 键创建一个 List<string>?

java - 存储 3 列 Oracle 表的最佳 Java 数据结构? 3列数组?还是双 map ?

java - 为什么不支持从entrySet()返回的集合的add/addAll操作?