Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 967
renegm Avatar asked Oct 09 '18 21:10

renegm


People also ask

How do I iterate through a Hashtable in PowerShell?

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.

What is @{} in PowerShell?

@{} 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'

What is GetEnumerator in PowerShell?

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.

How do I print a Hashtable in PowerShell?

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.


Video Answer


2 Answers

$ht | Select-Object -ExpandProperty Keys
like image 191
Nas Avatar answered Oct 12 '22 01:10

Nas


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 is keys 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
like image 4
Lance U. Matthews Avatar answered Oct 11 '22 23:10

Lance U. Matthews