tags:

views:

773

answers:

3

Given a list of items in powershell, how do I find the index of the current item from within a loop?

For example:

$letters = { 'A', 'B', 'C' }

$letters | % { 
 # Can I easily get the index of $_ here?
}

The goal of all of this is that I want to output a collection using Format-Table and add an initial column with the index of the current item. This way people can interactively choose an item to select.

A: 

Hi !

Not sure it's possible with an "automatic" variable. You can always declare one for yourself and increment it

$letters = { 'A', 'B', 'C' 
$letters | % {$counter = 0}{...;$counter++}

or use a for loop instead...

for($counter=0;$counter -lt $letters.Length;$counter++}{...}
Cédric Rup
+4  A: 

.NET has some handy utility methods for this sort of thing in System.Array:

PS> $a = 'a','b','c'
PS> [array]::IndexOf($a, 'b')
1
PS> [array]::IndexOf($a, 'c')
2

Good points on the above approach in the comments. Besides "just" finding an index of an item in an array, given the context of the problem, this is probably more suitable:

$letters = { 'A', 'B', 'C' }
$letters | % {$i=0} {"Value:$_ Index:$i"; $i++}

Foreach (%) can have a Begin sciptblock that executes once. We set an index variable there and then we can reference it in the process scripblock where it gets incremented before exiting the scriptblock.

Keith Hill
There may be a problem if the array contains duplicates...
Cédric Rup
Also you probably don't want to look up each index of an array item while iterating those items. That'd be linear search for every item; sounds like making one iteration O(n^2) :-)
Joey
+1  A: 
0..($letters.count-1) | foreach { "Value: {0}, Index: {1}" -f $letters[$_],$_}
Shay Levy