Can I add a key named 'keys' to a hashtable without overriding the 'keys' member
Asked Answered
H

1

4

It seems that I cannot add an arbitrary key name to a hashtable without overriding a member with that name if it already exists.

I create a hash table ($x) and add two keys, one and two:

$x = @{}

$x['one'] = 1
$x['two'] = 2

The added keys are then shown by evaluating $x.Keys:

$x.Keys

This prints:

one
two

If I add another key, named keys, it overrides the already existing member:

$x['Keys'] = 42

$x.Keys

This now prints:

42

I am not sure if I find this behavior desirable. I had expected $x.keys to print the key names and $x['keys'] to print 42.

Is it somehow possible to add a key named Keys without overriding the Keys member?

Hymenopteran answered 22/3, 2020 at 18:36 Comment(3)
The member property is still there —> $x.psobject.members['keys'].value.Cosby
They online documentation specifically calls out the scenario of key name and member property collisions. The official stance is to use $x.psbase.keysCosby
@Cosby why don't you post that as an answer?Consuela
C
3

In your example, the member property Keys still exists. It is just no longer accessible using the member access operator syntax object.property. You can see the property by drilling down into the PSObject sub-properties.

$x.PSObject.Members['Keys'].Value

The documentation for Hash Tables considers the scenario for property collisions. The recommendation for those cases is to use hashtable.psbase.Property.

$x.PSBase.Keys

For cases where collisions are unpredictable, you can use the hidden member method get_Keys() as in this question.

$hash.get_Keys()
Cosby answered 23/3, 2020 at 4:0 Comment(3)
If you don't know the keys upfront (e.g. for a solution like Powershell Merge 2 lists Performance), PSBase just moves the problem, consider: $hash = @{Keys = 'MyKeys'; PSBase = 'MyPSBase'}. Therefore I am often using the get_Keys() method for this. But as I can't find back were that was purposed and hardly any documentation on this method, I guess there is a pitfall behind this...Triptych
I just posted a official question for this: Is it correct to use the get_Keys() method for collectionsTriptych
@iRon, Thanks. I linked to your question. I think the online documentation should mention this.Cosby

© 2022 - 2024 — McMap. All rights reserved.