r/PowerShell • • Nov 22 '24

Question Hashtable syntax

why is it when i declare as hashtable, I can access its properties like an object?

PS C:\Users\john> $obj = @{
>>     Name = "John"
>>     Age = 30
>> }
PS C:\Users\john> $obj.Name
John

is this just syntactical sugar, or something? thought i would have to do this:

$obj[Name]
23 Upvotes

16 comments sorted by

View all comments

Show parent comment

10

u/surfingoldelephant Nov 22 '24 edited Oct 10 '26

why is it "hidden"?

Use Get-Member -Force to show the methods.

@{} | Get-Member -Force

Simply put, properties in .NET are backed by get/set methods (accessors). When you access a property in source code, it's really a method being called in the generated IL code. That's a massive oversimplification, but the point to illustrate is that each readable property for a given type has an associated get method. You would normally require reflection in C# to access these, but in PowerShell they're exposed.

Getter/setter methods are decorated with SpecialNameAttribute that IntelliSense typically looks for to determine if a member should be hidden from normal view (to prevent cluttering the editor with commonly undesired completions). It's for this same reason Get-Member requires -Force.

Why is it superior?

In member binding, dictionary keys are unfortunately preferred over type-native properties. PowerShell translates the member-access to indexing before it considers the type-native property.

For example, if you want a hash table's type-native Count but a key with the same name exists, .Count yields the key value, not the property value.

$ht = @{ Count = 100 }
$ht['Count'] # 100

# .Count yields the key value, not property value.
$ht.Count # 100

# To retrieve the type-native Count (# of key/value pairs):
$ht.get_Count() # 1

# Alternative approach using the ETS psbase property.
# ETS properties are preferred over keys.
$ht.psbase.Count # 1

Using the getter method avoids potential name collisions, especially when you don't know the contents of the dictionary upfront. There can't be any surprises with get_Count(), get_Values(), etc. The same can't be said for the equivalent properties.

You do need to be careful about null-value errors when calling the method. If that's a concern, use psbase.Count instead or check for $null first/use the null-conditional operator.