【问题标题】:Can Powershell Loop Through a Collection N objects at a time?Powershell可以一次循环遍历一个集合N个对象吗?
【发布时间】:2013-12-04 18:41:01
【问题描述】:

我想知道如何处理对象集合的循环,以组的形式处理该集合的元素,而不是像普通的 Foreach 循环那样单独处理。例如,而不是这个:

$items = get-vm
foreach ($item in $items) { do something }

我想这样做:

$items = get-vm
foreach ((5)$item in $items) {do something}

本质上,这句话的意思是说foreach 5 items in items做一些工作.....

谁能告诉我完成此任务所需的正确构造?

【问题讨论】:

  • 请退后一步,描述您要解决的实际问题,而不是您认为的解决方案。为什么您认为需要以 5 个为一组来处理 VM,而不是按顺序处理?

标签: loops powershell foreach


【解决方案1】:

我有这个:

 $array = 1..100
 $group = 10
 $i = 0

 do {
     $array[$i..(($i+= $group) - 1)]
     '*****'
     }
      until ($i -ge $array.count -1)

【讨论】:

  • FWIW 我想为我处理最后一组,即使它不包含完整的组大小,所以我将($i -ge $array.count -1) 更改为($i -gt $array.count -1)
  • 只是为了澄清@MarkSchultheiss 的评论。如果表达式中的余数为 1,则使用 -ge 只会隐藏最后一个组:$array.Length % $group。 (% 是模数运算符)因此,如果您不想显示余数为 1 的组,请使用 -ge,否则请使用 -gt。
【解决方案2】:

你们肯定给了我一些关于这个功能的好主意。我最终选择了以下内容:

#create base collection
$group = get-vm
$i = 0

do {
    new-variable -Name "subgroup$i" -value $group[0..4]
    ++$i
    $group = $group[5..$group.length]
}
while ($group.length -gt 0)

此代码产生多个子组,这取决于基本集合可被 5 整除的次数,在这种情况下,这是所需的子组数量......

【讨论】:

    【解决方案3】:

    更改为 Do...Until,每次将 counter 递增 5。

    $items = get-vm
    $i = 0
    do {
    #STUFF
    $i = $i + 5
    } until ($i -ge $items.count)
    

    (未经测试,但应该给你一个想法)

    编辑: 全面测试:

    $items = @()
    foreach ($item in (get-alias)) {
    $items += $item
    }
    
    $i = 0
    do {
    write-host $i
    $i = $i + 5
    } until ($i -ge $items.count)
    

    输出:

    0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 105 110 115 120 125 130 135

    编辑 2:

    $items = @()
    for($i=1; $i -le 75; $i++) {
    $items += $i
    }
    
    [int]$i = 0
    $outarray = @()
    do {
    $outarray += $items[$i]
    if ((($i+1)%5) -eq 0) {
        write-host $outarray
        write-host ---------
        $outarray = @()
    }
    
    $i = $i + 1
    } until ($i -gt $items.count)
    

    【讨论】:

    • 这个例子似乎显示了数组中每五个元素的处理。我正在寻求的是一次以五个批次处理整个阵列。使用您的活动,它只是打印元素,我希望看到五个数字组。例如:12345 678910 1112131415 等等......
    【解决方案4】:

    这是一个将项目收集成指定大小的块的函数:

    function ChunkBy($items,[int]$size) {
        $list = new-object System.Collections.ArrayList
        $tmpList = new-object System.Collections.ArrayList
        foreach($item in $items) {
            $tmpList.Add($item) | out-null
            if ($tmpList.Count -ge $size) {
                $list.Add($tmpList.ToArray()) | out-null
                $tmpList.Clear()
            }
        }
    
        if ($tmpList.Count -gt 0) {
            $list.Add($tmpList.ToArray()) | out-null
        }
    
        return $list.ToArray()
    }
    

    用法如下:

    ChunkBy (get-process) 10 | foreach { $_.Count }
    

    【讨论】:

      猜你喜欢
      • 2012-06-16
      • 1970-01-01
      • 2019-08-30
      • 2021-10-26
      • 1970-01-01
      • 2012-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多