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

This topic contains 3 replies, has 3 voices, and was last updated by  Dinesh Kumar 2 weeks ago.

  • Author
    Posts
  • #101936

    Dinesh Kumar
    Participant

    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

  • #101941

    Jeremy Corbello
    Participant

    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
            }
        }
  • #101942

    Don Jones
    Keymaster

    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.

You must be logged in to reply to this topic.