2015-04-08 40 views
1

我用下面的语句来填充数组: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 

但是,我用选择对象,并且在某些情况下,从多维数组中只选择一行。例如

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

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正在展开阵列。使用@可以确保返回一个数组。