Author Posts

June 6, 2018 at 5:41 pm

Hi,

I have a loop like below. In that, I want to compare next iteration value with current iteration value. If current value is not match with next value then I need to do some process. So I want to know like how to get the next Iteration value of a loop in powershell.

$var = ('abc','abc','bcd','cdf','cdf')
Foreach($i in $var){
If($i -ne $nextiterationvalue)
{
do something
}
else
{
do something
}
}

Thanks,
Dinesh

June 6, 2018 at 5:57 pm

In this case, you'd use a for loop to iterate over different entries of the array. See below:

for ($i = 0; $i -lt $var.count; $i++) {
    if ($var[$i] -ne $var[$i+1]) {
        do something
        }
    else {
        do something
        }
    }

June 6, 2018 at 5:57 pm

Within a ForEach, you can't. But you could do a For loop.

$array = @("some","stuff")

for ($x = 0; $x -lt $array.count; $x++) {
  $array[$x] # current item
  $array[$x + 1] # next item
  $array.count # max items
}

Note that the "next item" will fail once you're on the last item, so you'd need to add a check to not exceed $array.count.

June 8, 2018 at 8:06 am

Thanks! It worked very well.