Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell - Looping through objects in batches of 3

Tags:

powershell

I have an object which contains 7 items.

$obj.gettype().name
Object[]

$obj.length
7

I want to loop through in batches of 3. I do NOT want to use the modulus function, I actually want to be able to create a new object with just the 3 items from that batch. Pseudo code:

$j=0
$k=1
for($i=0;$i<$obj.length;$i+=3){
    $j=$i+2
    $myTmpObj = $obj[$i-$j] # create tmpObj which contains items 1-3, then items 4-6, then 7 etc
    echo "Batch $k
    foreach($item in $myTmpObj){
        echo $item
    }
    $k++
 }

Batch 1
item 1
item 2
item 3

Batch 2
item 4
item 5
item 6

Batch 3
Item 7

Regards, ted

like image 913
ted Avatar asked Dec 17 '22 14:12

ted


2 Answers

Your pseudo code is almost real. I have just changed its syntax and used the range operator (..):

# demo input (btw, also uses ..)
$obj = 1..7

$k = 1
for($i = 0; $i -lt $obj.Length; $i += 3) {

    # end index
    $j = $i + 2
    if ($j -ge $obj.Length) {
        $j = $obj.Length - 1
    }

    # create tmpObj which contains items 1-3, then items 4-6, then 7 etc
    $myTmpObj = $obj[$i..$j]

    # show batches
    "Batch $k"
    foreach($item in $myTmpObj) {
        $item
    }
    $k++
}

The output looks exactly as required.

like image 180
Roman Kuzmin Avatar answered Dec 25 '22 22:12

Roman Kuzmin


See if this one may work as required (I assume your item n is an element of $obj)

$obj | % {$i=0;$j=0;$batches=@{}}

if($i!=3 and $batches["Batch $j"]) { $batches["Batch $j"]+=$_; $i+=1 }
else {$i=1;$j+=1;$batches["Batch $j"]=@($_)}

} {$batches}

Should return an HashTable ($batches) with keys such as "Batch 1", "Batch 2", ... each key related to an array of three items.

like image 21
Emiliano Poggi Avatar answered Dec 26 '22 00:12

Emiliano Poggi