Array and ForEach

This topic contains 5 replies, has 3 voices, and was last updated by  Ondrej Zilinec 3 years, 9 months ago.

  • Author
  • #19596

    Ondrej Zilinec


    Is there a way to find out actual index of item in array if you use foreach() without using any variable as index counter?

    For example:

    foreach ($item in $items)
       write-host INDEX OF ITEM IN ITEMS?

    Thank you,

  • #19597

    Ondrej Zilinec

    Ooooo...I just found IndexOf() function. Isn't this too much CPU expensice to use instead of normal index counter variable? Does IndexOf() run through whole array and look for values?

    Thank you for answers,

  • #19598

    Don Jones

    Yeah, IndedOf does traverse the array until it finds what you're after, so it's not efficient on large arrays.

    And the original answer is no; the foreach script construct doesn't expose an index number. It's the construct that would have to do so, since it's the one doing the enumerating. You'd either have to use a counter variable, or refactor the loop into a for construct, which has an intrinsic counter variable.

  • #19599

    Don Jones

    BTW – be a bit careful about posting the first reply to your own posts. A lot of us use a "topics with no replies" view as a way of finding posts that need attention, and when you reply to yourself first, you take yourself off that list.

    • #19612

      Ondrej Zilinec

      Thank you 🙂 OK, I will not answer my own questions 🙂 I woll rather edit question.

  • #19605

    Raymond Slieff

    Don't forget to test how fast the different methods work with the measure-command cmdlet. Once you have figured out multiple ways to do something it is good to see how fast each method is, although speed is not always the only concern.

You must be logged in to reply to this topic.