In PowerShell you can get all keys from a Hashtable
using the Keys
property:
$ht=@{
"1"="10";
"2"="20";
}
$ht.Keys
This returns:
2
1
BUT this:
$ht=@{
"Keys"="Keys text";
"text1"="text1111"
}
$ht.Keys
will return Keys text
(the value of the Keys
item)
Is there any way to force .Keys
to return the Keys
property instead the Keys
item's value?
In the first method, the one that I prefer, you can use the GetEnumerator method of the hash table object. In the second method, instead of iterating over the hash table itself, we loop over the Keys of the hash table. Both of these methods produce the same output as our original version.
@{} in PowerShell defines a hashtable, a data structure for mapping unique keys to values (in other languages this data structure is called "dictionary" or "associative array"). @{} on its own defines an empty hashtable, that can then be filled with values, e.g. like this: $h = @{} $h['a'] = 'foo' $h['b'] = 'bar'
GetEnumerator. A hash table is a single PowerShell object, to sort, filter or work with the pipeline you can unwrap this object into it's individual elements with the GetEnumerator() method.
Printing hashtable: To print /display a hashtable, just type the variable name in which hashtable is saved. The above command displays a table with two columns, one for keys and the other one for the associated values for the keys.
$ht | Select-Object -ExpandProperty Keys
This seems like a bug since the syntax to retrieve the Keys
entry is superseding the HashTable
's Keys
property, though I could see one expecting it to behave either way. According to the Adding a key of 'keys' to a Hashtable breaks access to the .Keys property issue on GitHub, this is a bug but would require a breaking change to correct, so the workaround below was added to the documentation.
According to 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 iskeys
and you want to return the collection of Keys, use this syntax:
$hashtable.PSBase.Keys
You could also retrieve the property value through reflection...
PS> $ht.GetType().GetProperty('Keys').GetValue($ht)
text1
Keys
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With