powershellpowershell-5.1invoke-restmethod

Powershell: Why is $object.AProperty -ne $object['Aproperty']


I am very confused. I'm used to in most programming languages to where referencing a property in the dot notation (e.g. $object.AProperty) is the exact same thing as referencing it in what I'll call the "hashtable" notation (e.g. $object['code']).

However, I've got an Invoke-RestMethod request that is returning content from a page. If in debugging I output: $Object['code']

I get $null

And yet, if I output: $Object.code

I get the value that is actually within it, which is "200".

Why on earth would this happen?

I can work past this issue by using the other notation, but I'm so confused as to why it happens. I was surprised to find that in PowerShell, even the following is proper: $Object.$property

As a result, this is a non-issue for my code, but I'd like to understand what is happening.


Solution

  • As I wrote in the comment, hashtables are objects, but not all objects are hashtables. In Powershell, you can only use hashtable notation on objects that are actually hashtables; for everything else, you must use dot notation. Generally, using hashtable notation on a non-hashtable will return a null value rather than throwing an error; if you want to force an error to be thrown, you should Set-Strictmode -Version "Latest", which will enforce the tightest interpretation of Powershell rules (such as this, or setting a variable before referencing the value). Note that in both dot notation and hashtable notation, the index/member name can be generated by an expression, but for a non-hashtable, an error will be thrown if the expression does not evaluate to the name of an existing member.