Can Powershell Loop Through a Collection N objects at a time?

后端 未结 4 1448
感情败类
感情败类 2020-12-16 08:10

I am wondering how one would tackle looping through a collection of objects, processing the elements of that collection in groups instead of singularly, as is the case in no

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-16 08:37

    Change to Do...Until, increment counter by 5 each time.

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

    (Untested, but should give you an idea)

    EDIT: Fully tested:

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

    Output:

    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

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

提交回复
热议问题