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

后端 未结 4 1449
感情败类
感情败类 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:38

    Here's a function that will collection items into chunks of a specified size:

    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()
    }
    

    The usage would be something like:

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

提交回复
热议问题