powershell多维数组和foreach

时间:2015-04-08 11:36:41

标签: arrays powershell foreach

我使用以下语句来填充数组:

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))
    }
}

输出几乎是你所期望的:

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

但是,我使用select-object,在某些情况下,只从多维数组中选择一行。 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"
}

而现在,foreach反复遍历数组中的每个对象:

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

我可以理解为什么会发生这种情况,我认为答案不是使用foreach。我有什么方法可以改变这种行为,这样我仍然可以使用foreach吗?

1 个答案:

答案 0 :(得分:1)

添加at符号

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

您的问题是您的Where-Object只匹配一行。如果你匹配的那一行我们就不会注意到了。

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

PowerShell正在展开数组。使用@可以确保返回数组。