PowerShell - 如何使用 $_.Key 作为 $object 属性? [英] PowerShell - How to use a $_.Key as $object property?

查看:35
本文介绍了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' }

这篇关于PowerShell - 如何使用 $_.Key 作为 $object 属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆