Array and ForEach


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,

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,

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.

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.

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.

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