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?

René Nyffenegger
  • 39,402
  • 33
  • 158
  • 293

1 Answers1

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()
AdminOfThings
  • 23,946
  • 4
  • 17
  • 27
  • If you don't know the keys upfront (e.g. for a solution like [Powershell Merge 2 lists Performance](https://stackoverflow.com/q/46091947/1701026)), `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... – iRon Mar 23 '20 at 08:18
  • I just posted a official question for this: [Is it correct to use the get_Keys() method for collections](https://stackoverflow.com/q/60810458/1701026) – iRon Mar 23 '20 at 09:02
  • 1
    @iRon, Thanks. I linked to your question. I think the online documentation should mention this. – AdminOfThings Mar 23 '20 at 12:26