Cataster
Cataster

Reputation: 3521

How to Loop through pscutomobject array and add an extra property?

suppose i have the following pscutomobject array script

$pscoArray = @()

foreach($server in $Servers) {
    $pscoArray += [PSCustomObject]@{
        Server = $server
    }
}                   

$iteration = 0

how do i loop through the resulting $pscoArray and add to it a new member called 'iteration' and increment that based on number of objects that already exist in the array?

i.e.

$pscoArray = $pscoArray | %{ Add-Member -MemberType NoteProperty -Name 'iteration' -Value $iteration; 'iteration' = $iteration++}

ultimate output should look like this, assuming there are 3 servers in this example

iteration Server
------    ------
1         server1
2         server2
3         server3

so iteration has to be added as a member at position 0, at the beginning of the pscustomobject, although i dont know how would i do that either

p.s. i know i can just add iteration directly in the forloop, but i need this for a different purpose.

Upvotes: 0

Views: 166

Answers (1)

Theo
Theo

Reputation: 61068

If this is the code that generates your array

$Servers = 'svr1', 'svr2', 'svr3'
$pscoArray = foreach($server in $Servers) {
    [PSCustomObject]@{
        Server = $server
    }
}

Then the simplest way of doing this may be by using a for(..) loop

# add a new property called "iteration" to each member of the array
for ($i = 0; $i -lt $pscoArray.Count; $i++) {
    $pscoArray[$i] | Add-Member -MemberType NoteProperty -Name 'iteration' -Value ($i + 1)
}

$pscoArray

Output:

Server iteration
------ ---------
svr1           1
svr2           2
svr3           3


Update

If you want to get the iteration property listed first, you could do:

# add a new property called "iteration" as first property to each member of the array
for ($i = 0; $i -lt $pscoArray.Count; $i++) {
    $pscoArray[$i] = $pscoArray[$i] | Select-Object @{Name = 'iteration'; Expression = {$i + 1}}, *
}

$pscoArray

Output:

iteration Server
--------- ------
        1 svr1  
        2 svr2  
        3 svr3

Upvotes: 2

Related Questions