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
3
u/purplemonkeymad Nov 22 '24
Yea it was a nice shortcut that was added at some point, i want to say maybe PS3.0?
19
u/surfingoldelephant Nov 22 '24 edited Oct 10 '26
$obj['Name']is syntactic sugar for$obj.Item('Name').Item()in PowerShell is aParameterizedProperty, which is how PS exposes a type's indexer. In .NET,Itemis the default indexer name, but some types use a custom name ([string]'s indexer is namedChars).Internally, PowerShell translates member-access (
$obj.Name) into indexing for most dictionary types during member binding. This was introduced early on for convenience. Namely, because.Nameis easier to type than['Name']. It also means you don't need to differentiate between dictionaries and other types.While convenient, there are quite a few reasons to avoid the feature, at least outside the shell. It's slower, broken with some types of dictionary, less feature rich (no array slicing or access to indexer overloads) and is inconsistently implemented in respect to type-native vs extended type system (ETS) properties.
In general, if you want to write robust code:
[]to access dictionary keys.Don't use
.to access type-native dictionary properties (e.g.,Count,KeysorValues) unless you know for certain the dictionary doesn't contain matching keys.get_Count(),get_Keys(),get_Values()) orpsbase($obj.psbase.Count)instead..to access ETS properties attached to the dictionary (this is rarely needed).2
u/-c-row Nov 23 '24
IMHO It's not just synthetical sugar and like to show an example. I have a hash table with settings for different environments. The environments have much in common, but also individual parts depending if it is for development, testing or production.
Now I can combine them by using
$setting["common", "dev"]Furthermore I can use it also this way:The output would be the combination of the common and the test where I can address the all the same way.
This way I can access them easy and flexible.
1
u/Szeraax Nov 22 '24
The old way is nice when you want to use properties though.
The alternative I guess would be something like:
Which is just... major yikes. Don't know if that would even work, tbh.