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

Pet*_*ive 2 powershell

我有一个看起来像这样的物体。

$test = {
"displayName": "Testname"
"userAge": 22
}
Run Code Online (Sandbox Code Playgroud)

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

$friendlyNames = ["Display name", "User age"]
Run Code Online (Sandbox Code Playgroud)

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

$test = {
"Display name" = "Testname"
"User age" = 22
}
Run Code Online (Sandbox Code Playgroud)

mkl*_*nt0 5

# 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
Run Code Online (Sandbox Code Playgroud)

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

# 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
Run Code Online (Sandbox Code Playgroud)

笔记:

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

  • 使用(有序)哈希表是迭代创建(有序)键值对集合的有效方法,稍后只需将其转换[pscustomobject].

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