gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 18:01:14 24 4
gpt4 key购买 nike

在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com