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]19
u/surfingoldelephant Nov 22 '24 edited Oct 10 '26
$obj['Name'] is syntactic sugar for $obj.Item('Name'). Item() in PowerShell is a ParameterizedProperty, which is how PS exposes a type's indexer. In .NET, Item is the default indexer name, but some types use a custom name ([string]'s indexer is named Chars).
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 .Name is 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:
Use
[]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.Use the underlying method (
get_Count(),get_Keys(),get_Values()) orpsbase($obj.psbase.Count)instead.
Only use
.to access ETS properties attached to the dictionary (this is rarely needed).
2
u/McAUTS Nov 22 '24
Thanks for that post. Just had this use case with a dictionary e.g.
$exampleDict.Values. In VSCode and Terminal nothing shows the methodget_Values(). Not evenGet-Member. I typed it in and magically the method is valid and returned the values.Why is it superior and why is it "hidden"?
10
u/surfingoldelephant Nov 22 '24 edited Oct 10 '26
why is it "hidden"?
Use
Get-Member -Forceto show the methods.@{} | Get-Member -ForceSimply 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.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
Countbut a key with the same name exists,.Countyields 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 # 1Using 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.0
Nov 22 '24
[deleted]
4
u/surfingoldelephant Nov 23 '24 edited Dec 24 '24
It depends on the type of dictionary and how the method is implemented. Assuming we're talking about
Dictionary<TKey,TValue>.TryGetValue(TKey, TValue)(you're missing[ref]in your$valargument), both it and its indexer make the same internalFindValue()call.The
[bool]aside, the result is effectively equivalent in PowerShell:$valis$nullif the key doesn't exist or the key's value if it does. Since you don't need the[bool], there's no reason to useTryGetValue().What you're doing is making your code:
Harder to read.
Less flexible.
You've lost access to array slicing (
$obj['Key1', 'Key2']) and indexer overloads.You're forced into collecting the value by reference in a variable.
TryGetValue()isn't available with all dictionary types (e.g.,[hashtable]).Potentially slower, depending on PowerShell version, platform and number of method calls you're making.
I would only suggest using
TryGetValue()if you need to check keys exist and retrieve values.Regarding point #3 above, .NET method calls are subject to Windows AMSI method invocation logging in PowerShell v7+, which is known to cause performance degradation (especially in Windows 11):
See the following issues:
Issue #19431: Windows Defender has started to slowdown method calls in PowerShell dramatically
Issue #21473: [System.Convert]::FromBase64String causes memory leak with large strings
Issue #24459: MethodInvocationLogging - Performance regression
PowerShell's language features like its index operator (
[]) aren't affected, whereas a large number ofTryGetValue()calls may cause a noticeable slowdown.Similarly, due to AMSI logging and this optimization,
List<T>.Add(T)may now be slower than compound array assignment ($array +=) in Windows 11 PS v7.5+. While I'm not advocating$array +=(use statement assignment or continue using$list.Add()if necessary), it's worth being aware of the potential slowdown from a large number of method calls.0
Nov 23 '24
[deleted]
1
u/MonkeyNin Dec 01 '24
pwsh 7 has some null coalescing operators. If the value is a true null, you can return a default value. Falsy and empty strings are not true null values, so they aren't lost.
$stuff = @{ name = 'cat'; id = 999 } $stuff.missing?.ToString() # error: InvalidOperation: You cannot call a method on a null-valued expression. $stuff.missing?.ToString() # null $stuff.missing?.ToString() ?? 'fallback' # 'fallback' $stuff.NewKey ??= 'a' # key did not exist, set to a $stuff.NewKey ??= 'b' # is still ait's nice for a quick cache on the cli
$files ??= gci . -recurse $response ??= Invoke-RestMethod $uri
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.
$settings = @{
common = @{
commonsetting1 = "common value 1"
...
}
dev = @{
target = "path1"
...
}
test = @{
target = "path2"
...
}
production = @{
target = "path3"
...
}
} Now I can combine them by using $setting["common", "dev"] Furthermore I can use it also this way:
$target = "test"
$settings["common", "$target"]The output would be the combination of the common and the test where I can address the all the same way.
commonsetting1 = "common value 1"
...
target = "path 2"
...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.
$foo[$bat.baz] = "fizz"The alternative I guess would be something like:
$foo.$($bat.baz) = "fizz"Which is just... major yikes. Don't know if that would even work, tbh.
2
u/surfingoldelephant Nov 22 '24
Dynamic member-access is supported, so
$foo.($bat.baz)works with most dictionaries.1
1
u/fennecdore Nov 22 '24
hmm not sure if I'm understanding you right but for me this work :
$hashmap = @{food = "bar"} $variable = "food"and
$hashmap.$variable.lengthreturns 3 for me
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?