Powershell - Sifting Objects in Batch 3

I have an object containing 7 elements.

$obj.gettype().name Object[] $obj.length 7 

I want to execute a loop in batches of 3. I DO NOT want to use the module function, I really want to be able to create a new object with only three elements from this lot. Pseudocode:

 $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

+4
source share
2 answers

Your pseudo code is almost real. I just changed my 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 result looks exactly as required.

+7
source

See if this work can work as needed (I assume your element n is the $obj element)

  $ 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 HashTable ( $batches ) with keys such as "Batch 1" , "Batch 2" , ... each key is associated with an array of three elements.

0
source

All Articles