PowerShell - How to use a $_.Key as $object property?

Viewed 315

I have a hashtable like so:

$hash = @{
    One="One"
    Two="Two"
    Three="Three"
    }

Doing this does not work:

$hash.getEnumerator() | foreach {
  $object.$_.Key = $_.Value
}

However this words:

$hash.getEnumerator() | foreach {
  $test = $_.Key
  $object.$test = $_.Value
}
1 Answers

PowerShell allows you to use expressions as property names, which is what you successfully used in $object.$test: the value of variable $test served as the property name.

However, depending on the complexity of the expression, you may need (...) to delineate it:

Therefore, you must use $object.($_.Key) rather than $object.$_.Key - the latter would be interpreted as nested property access.


Taking a step back:

PowerShell allows you to construct and initialize types that have a parameter-less constructor and public properties directly from a hashtable; e.g. (PSv5+):

# Type (class) with parameterless constructor and public properties.
class Foo {
  [string] $Bar
  [int]    $Baz
}

# Instantiate [Foo] and set its properties from a hashtable
$newFoo = [Foo] @{ Baz = 42; Bar = 'none' }
Related