Array and ForEach

This topic contains 5 replies, has 3 voices, and was last updated by Profile photo of Ondrej Zilinec Ondrej Zilinec 2 years, 1 month ago.

  • Author
    Posts
  • #19596
    Profile photo of Ondrej Zilinec
    Ondrej Zilinec
    Participant

    Dudes!

    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:

    [array]$items="a","b","c"
    foreach ($item in $items)
       {
       write-host INDEX OF ITEM IN ITEMS?
       }
    

    Thank you,

  • #19597
    Profile photo of Ondrej Zilinec
    Ondrej Zilinec
    Participant

    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
    Profile photo of Don Jones
    Don Jones
    Keymaster

    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
    Profile photo of Don Jones
    Don Jones
    Keymaster

    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
      Profile photo of Ondrej Zilinec
      Ondrej Zilinec
      Participant

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

  • #19605
    Profile photo of Raymond Slieff
    Raymond Slieff
    Participant

    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.