How to compare current and next Iteration values of foreach loop in Powershell

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

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
        }
    }

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.

Thanks! It worked very well.