Search code examples
powershellsyntactic-sugar

Can $obj.psObject.properties[$key].value be abbreviated


In order to get the value of a object's property whose name is stored in a variable, I use the following construct:

# Create object
$obj = new-object psObject -property @{ num = 42; txt = 'Hello world' }

# Name of property whose value I want:
$key = 'txt'

# Get value
$val = $obj.psObject.properties[$key].value
$val

I am wondering if $obj.psObject.properties[$key].value can somehow be abbreviated.


Solution

  • Getting the value directly from a property where the property name (txt) is stored in a variable ($key) can be done like this;

    $obj.$key