Question

I am a self-taught, newbie programmer, and I feel like this is a really basic question, the kind I'd be able to answer if I had actually studied computer science :P In my searching of the intertrons and StackOverflow I haven't been able to find the answer I'm looking for. So I hope someone can indulge me.

I have a collection of objects. I want to operate on them five at a time, and then move on to the next five. The context is rebooting a bunch of VMs; I'm being asked to stagger them so that the hosts aren't slammed with all of the VMs rebooting at once.

I sense that the right path is a for i loop in some capacity, and not foreach. I also feel like it could be a combination of do-until and for i but I can't sift the answer out of my brain.

I could probably do it by removing objects from the collection, but that feels like the "wrong" way to do this, even if it would work.

I'm doing this with Powershell and PowerCLI, but I feel as though the logic I'm trying to understand is more basic than being dependent on any language, so even if you're not familiar with Powershell, I'm interested in your answer.

Edit: Based on David's answer below, the following code seems to be what I'm looking for:

$someLetters = @("a","b","c","d","e","f","g","h","i","j","k")

for($i=0; $i -lt $someLetters.length; $i+=5)
{
    Write-Host ("the letter is " + $someLetters[$i] + " and i is " + $i)
    Write-Host ("the letter is " + $someLetters[$i+1] + " and i is " + $i)
    Write-Host ("the letter is " + $someLetters[$i+2] + " and i is " + $i)
    Write-Host ("the letter is " + $someLetters[$i+3] + " and i is " + $i)
    Write-Host ("the letter is " + $someLetters[$i+4] + " and i is " + $i)
    write-host "finished block of five"
}

gives the output:

the letter is a and i is 0
the letter is b and i is 0
the letter is c and i is 0
the letter is d and i is 0
the letter is e and i is 0
finished block of five
the letter is f and i is 5
the letter is g and i is 5
the letter is h and i is 5
the letter is i and i is 5
the letter is j and i is 5
finished block of five
the letter is k and i is 10
the letter is  and i is 10
the letter is  and i is 10
the letter is  and i is 10
the letter is  and i is 10
finished block of five

Thank you David!

Was it helpful?

Solution

You didn't say what kind of container your objects are in. I'll assume it's an array. So, you could do something like this:

for($i=0; $i -lt $objectArray.length; $i+=5)
{
    #do something with $objectArray[$i]
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top