PowerShell - 如何使用 $_.Key 作为 $object 属性?

问题描述:

我有一个像这样的哈希表:

I have a hashtable like so:

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

这样做不起作用:

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

然而这句话:

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

PowerShell 允许你使用 表达式 作为属性名,这就是你在 $object.$test:变量$test的值作为属性名.

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:

因此,您必须使用 $object.($_.Key) 而不是 $object.$_.Key - 后者将被解释为 嵌套属性访问.

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

退一步:

PowerShell 允许您直接从哈希表构造和初始化具有无参数构造函数和公共属性的类型;例如(PSv5+):

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' }