如何从包含 "Keys" 和 "Values" 文本的哈希表中检索所有键?

How to retrieve all keys from hashtable containing "Keys" and "Values" text?

在 PowerShell 中,您可以使用 Keys 属性:

Hashtable 获取所有密钥
$ht=@{
    "1"="10";
    "2"="20";
}
$ht.Keys

这个returns:

2
1

但是这个:

$ht=@{
    "Keys"="Keys text";
    "text1"="text1111"
}
$ht.Keys

将returnKeys textKeys项的值)

有什么方法可以强制 .Keys 到 return Keys 属性 而不是 Keys 项的值?

这似乎是一个错误,因为检索 Keys 条目的语法正在取代 HashTableKeys 属性,尽管我可以看出有人期待它以任何一种方式行事。根据 GitHub 上的 Adding a key of 'keys' to a Hashtable breaks access to the .Keys property 问题,此 一个错误,但需要进行重大更改才能更正,因此将以下解决方法添加到文档中。

根据about_Hash_Tables

If the key name collides with one of the property names of the HashTable type, you can use PSBase to access those properties. For example, if the key name is keys and you want to return the collection of Keys, use this syntax:

$hashtable.PSBase.Keys

您还可以通过反射检索 属性 值...

PS> $ht.GetType().GetProperty('Keys').GetValue($ht)
text1
Keys
$ht | Select-Object -ExpandProperty Keys