arrays - powershell多维数组和foreach

标签 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 并且在某些情况下仅从多维数组中选择一行。例如

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?

最佳答案

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

关于arrays - powershell多维数组和foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29513496/

相关文章:

java - 无法将数组传递到方法中

powershell - 如果在Powershell中安装应用程序时Else语句给出错误

c++ - 我可以通过 for_each <algorithm> 在 C++ 中的指针 vector 上调用 `delete` 吗?

r - 我如何使用 R 在 Stata 中执行类似 foreach 的操作?

php - 在 php foreach 循环中回显 SQL PDO 对象

javascript - 如何按副标题和标题(而不是仅按其中之一)进行筛选?

java - 尝试在 remove() 方法中从数组中删除字符串单词时出现 NullPointerException 错误

javascript - JSON - 对象中的数组中的对象 - 如何使用 JS 解析循环?

powershell - 如何确定执行函数的文件名

powershell - 如何从已安装的更新窗口获取所有详细信息