none
In a Foreach, is there a good way to tell what iteration you are in through the loop RRS feed

  • Question

  • $a = "hello","goodbye","never"

    foreach ($b in $a) {

    if (-is there something I can use here- = 1) {      ----  then do this ----}

    else { --------  do this   ----}

    }

    OK, I know I can add a counter inside the loop (ie. $i++).  But what I am asking is there a property of $a (or $b) that I can reference to know what iteration of the loop that I am in, or is there some other $variable that I can reference?  Setting up a separate variable as the counter just seems awkward/archaic to find out what iteration of the object I am in.

    Wednesday, May 13, 2015 3:20 PM

Answers

  • You can use this example to get started.

    $a = "hello","goodbye","never","something","something else"
    
    foreach ($b in $a) {
    
    if ($a.indexof($b) -eq 1) { write-host "This is item at index number 1" }
    
    else { write-host "something else" }
    
    }
    Keep in mind that the index starts at 0.



    • Edited by ThmsRynr Wednesday, May 13, 2015 3:26 PM clarity
    • Marked as answer by dcybela Wednesday, May 13, 2015 8:28 PM
    Wednesday, May 13, 2015 3:25 PM

All replies

  • You can use this example to get started.

    $a = "hello","goodbye","never","something","something else"
    
    foreach ($b in $a) {
    
    if ($a.indexof($b) -eq 1) { write-host "This is item at index number 1" }
    
    else { write-host "something else" }
    
    }
    Keep in mind that the index starts at 0.



    • Edited by ThmsRynr Wednesday, May 13, 2015 3:26 PM clarity
    • Marked as answer by dcybela Wednesday, May 13, 2015 8:28 PM
    Wednesday, May 13, 2015 3:25 PM
  • Array IndexOf method doesn't exist in PowerShell 2.0, so that answer may be a non-starter.

    If you need to keep track of array index, then just use for instead of foreach.


    $a = "hello","goodbye","never"
    for ( $i = 0; $i -lt $a.Count; $i++ ) {
      "{0}. {1}" -f $i,$a[$i]
    }
    


    -- Bill Stewart [Bill_Stewart]

    Wednesday, May 13, 2015 3:46 PM
    Moderator