在 PowerShell 中更新哈希表数组中的哈希表值

问题描述 投票:0回答:1

我想添加/更新数组中对象的属性。

我有对象数组,我想在其中添加具有范围值的属性“id”。

[array] $idRange= @(1, 2, 3)

[hashtable[]] $aoo= @(@{})*$idRange.Count
foreach ($id in $idRange) {
  $i = $idRange.IndexOf($id)
  $aoo[$i].set_Item('id', $id)
}

预期结果是

@(@{'id'=1}, @{'id'=2}, @{'id'=3})

但是 .set_Item 写入数组中的所有项目,并且过度迭代值就像

@(@{'id'=1}, @{'id'=1}, @{'id'=1})
@(@{'id'=2}, @{'id'=2}, @{'id'=2})
@(@{'id'=3}, @{'id'=3}, @{'id'=3})

我做错了什么?

arrays powershell object properties
1个回答
0
投票

你想太多了。

# Create the Id array.  
# Prepending [int[]] forces it to be a Int Array, otherwise it will be a Object
# Array containing Int objects. 
[int[]]$idRange = 1, 2, 3

# Assigning a Foreach to a Variable causes every Success Stream(stdOut) output
# in the loop to be added to the Variable as a array element.  
# This is more efficient than adding each element individually unless you need
# to add\remove elements later: in that case look for Lists.   
# Prepending [hashtable[]] forces it to be a Hastables Array, otherwise it will
# be a Object Array containing Hashtable objects. 
[hashtable[]]$aoo = foreach ($id in $idRange) {
    # this creates a Single Property Hashtable with the property Id with value
    # $id and pushes it to the Success Stream, thus being captured by the $aoo
    # variable as one element of its array.   
    @{id = $id }
}

$aoo

PS ~> .\test.ps1

Name                           Value
----                           -----
id                             1
id                             2
id                             3
© www.soinside.com 2019 - 2024. All rights reserved.