biscuitNinja
biscuitNinja

Reputation: 21

powershell multi-dimensional array and foreach

I use the following statements to populate an array:

for ([int]$i=1; $i -lt 4; $i++)
{
    for ([int]$j=11; $j -lt 32; $j=$j+10)
    {
         $myRegularArray += ,($i, $j, [int](($i +1) * $j))
    }
}

And the output is pretty much what you'd expect:

foreach ($row in $myRegularArray)
{
    write-host "$($row[0]) rampant frogs, $($row[1]) horny toads & $($row[2]) bottles of beer"
}

1 green frogs, 11 horny toads & 22 bottles of beer
1 green frogs, 21 horny toads & 42 bottles of beer
1 green frogs, 31 horny toads & 62 bottles of beer
2 green frogs, 11 horny toads & 33 bottles of beer
2 green frogs, 21 horny toads & 63 bottles of beer
2 green frogs, 31 horny toads & 93 bottles of beer
3 green frogs, 11 horny toads & 44 bottles of beer
3 green frogs, 21 horny toads & 84 bottles of beer
3 green frogs, 31 horny toads & 124 bottles of beer

However, I use select-object and in some scenarios only a single row is selected from the muti-dimensional array. e.g.

foreach ($row in ($myRegularArray | where-object { $_[2] -eq 124 }))
{
    write-host "$($row[0]) rampant frogs, $($row[1]) horny toads & $($row[2]) bottles of beer"
}

And now instead the foreach iterates through each object in the arrays single dimension:

3 rampant frogs,  horny toads &  bottles of beer
31 rampant frogs,  horny toads &  bottles of beer
124 rampant frogs,  horny toads &  bottles of beer

I can sort of see why this happens, and I figure the answer is not to use foreach. I there any way of changing this behaviour so that I can still use foreach?

Upvotes: 2

Views: 8004

Answers (1)

Matt
Matt

Reputation: 46730

Add an at sign

foreach ($row in @($myRegularArray | where-object { $_[2] -eq 124 }))
{
    write-host "$($row[0]) rampant frogs, $($row[1]) horny toads & $($row[2]) bottles of beer"
}

You issue is that your Where-Object was only matching one row. If you had matched more that one row we would not have noticed.

where-object { $_[2] -gt 60 }

PowerShell was unrolling the array. Using the @ can ensure an array is returned.

Upvotes: 2

Related Questions