arrayspowershellobjectproperties

Updating hash table value in array of hash table in PowerShell


I want to add/update property of object in array.

I have array of objects, where i want to add property 'id' with value from range.

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

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

Expected result is to have @(@{'id'=1}, @{'id'=2}, @{'id'=3})

but .set_Item writes in all items in array and over iterating values are like

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

what am I doing wrong?


Solution

  • You are overthinking.

    # 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