Powershell break a long array into a array of array with length of N in one line?

前端 未结 6 2021
梦毁少年i
梦毁少年i 2020-12-18 02:24

For example, given a list 1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8 and a number 4, it returns a list of list with length of 4, that is (1, 2, 3, 4), (5, 6, 7, 8),

6条回答
  •  不知归路
    2020-12-18 02:40

    This is a bit old, but I figured I'd throw in the method I use for splitting an array into chunks. You can use Group-Object with a constructed property:

    $bigList = 1..1000
    
    $counter = [pscustomobject] @{ Value = 0 }
    $groupSize = 100
    
    $groups = $bigList | Group-Object -Property { [math]::Floor($counter.Value++ / $groupSize) }
    

    $groups will be a collection of GroupInfo objects; in this case, each group will have exactly 100 elements (accessible as $groups[0].Group, $groups[1].Group, and so on.) I use an object property for the counter to avoid scoping issues inside the -Property script block, since a simple $i++ doesn't write back to the original variable. Alternatively, you can use $script:counter = 0 and $script:counter++ and get the same effect without a custom object.

提交回复
热议问题