更改 PowerShell 对象属性名称,保留值

时间:2021-05-30 20:45:59

标签: powershell

我有一个看起来像这样的对象。

$test = {
"displayName": "Testname"
"userAge": 22
}

我有一个看起来像这样的数组。

$friendlyNames = ["Display name", "User age"]

$friendlyNames 数组索引的设置方式将始终与对象属性顺序匹配。 是否可以自动替换它并最终得到一个看起来像这样的对象?

$test = {
"Display name" = "Testname"
"User age" = 22
}

1 个答案:

答案 0 :(得分:4)

# The sample input object.
$test = [pscustomobject] @{
  displayName = "Testname"
  userAge = 22
}

# The array of new property names.
$friendlyNames = 'Display name', 'User age'

# Use an ordered hashtable as a helper data structure
# to store the new property names and their associated values as
# name-value pairs.
$oht = [ordered] @{}; $i = 0
$test.psobject.Properties.ForEach({
  $oht[$friendlyNames[$i++]] = $_.Value
})

# Convert the ordered hashtable to an object ([pscustomobject])
$testTransformed = [pscustomobject] $oht

输出 $testTransformed 产量(默认情况下应用表格格式,因为对象具有 4 个或更少的属性;管道到 Format-List 以在其自己的行中查看每个属性):

Display name User age
------------ --------
Testname           22

注意:

  • PowerShell 在任何对象上公开 .psobject 作为丰富的反射源,.psobject.Properties 返回描述对象公共属性的对象集合,每个对象都有 .Name.Value 属性。

  • 使用(有序)hashtable 是迭代创建(有序)键值对集合的有效方法,该集合稍后可以转换为自定义对象只需将其强制转换为 [pscustomobject]

    • 事实上,自定义对象的文字语法([pscustomobject] @{ ... })表明了这一点(用于构造上面的$test),但请注意这是语法糖,因为它可以直接(更有效地)构建 [pscustomobject] 实例。