r/PowerShell • u/TTwelveUnits • 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
Johnis this just syntactical sugar, or something? thought i would have to do this:
$obj[Name]
23
Upvotes
View all comments
Show parent comment
10
u/surfingoldelephant Nov 22 '24 edited Oct 10 '26
Use
Get-Member -Forceto show the methods.Simply put, properties in .NET are backed by
get/setmethods (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 associatedgetmethod. You would normally require reflection in C# to access these, but in PowerShell they're exposed.Getter/setter methods are decorated with
SpecialNameAttributethat 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 reasonGet-Memberrequires-Force.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
Countbut a key with the same name exists,.Countyields the key value, not the property value.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.Countinstead or check for$nullfirst/use the null-conditional operator.