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

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 a

it's nice for a quick cache on the cli

$files ??= gci . -recurse 

$response ??= Invoke-RestMethod $uri