XenApplePie

When Trouble Comes Along, You Must Skip It! : Using -Skip With Select-Object And Do Loop

While working on the script to release licenses, I ran into a dilemma I had encountered before. I needed to move through a set of records in an array, but not the whole array at one time. Since I was limited to 100 licenses released per Invoke-RestMethod, I needed a way to do that without having to call it multiple times. I had also encountered this at other times and usually resorted to just doing the call multiple times and limiting my results to the number I wanted to iterate through. I didn’t think that was efficient and wanted to find a better way. So in looking around, I found this site: ResultSize. Using that wonderful -Skip, I just added that to a Do .. Until loop to get where I wanted to go.

So applying what I wanted to do was 100 records at a time, I set my $toSkip counter to 0 to start and the $smallerCount set to the value of the $someArray.count size inside the If check just before the Do loop. After each loop, I would increment the $toSkip and decrement the $smallerCounter by the same amount and set the Until condition to be less that the increment / decrement amount. Then I copied the same code for after the Until condition is met to run one more time with the amount of objects remaining in the array. For example, if it had 435 items in it, it would run 4 times with 100 items each time and one last time with 35 items in it.

$someArray = "lots", "of", "stuff", "here"

if($someArray.count -gt 100){

$smallerCounter = $someArray.Count
$toSkip = 0

Do{

$smallerList = $someArray | Select-Object -Skip $toSkip -first 100

foreach($small in $smallerList){

Do Stuff

}

$toSkip += 100
$smallerCounter -= 100

} Until ($smallerCounter -lt 100)

$smallerList = $someArray | Select-Object -Skip $toSkip -first $smallerCounter

foreach($small in $smallerList){

Do Stuff

}

}
Exit mobile version