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

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.