Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PS: Get index in an array list

Tags:

powershell

I have an array of strings. Not sure if there is simple way to get the index of an item first found in the array?

# example array
$array = "A", "B", "C"
$item = "B"
# the following line gets null, any way to get its index?
$index = $array | where {$_ -eq $item} | ForEach-Object { $_.Index }

I could do it in a loop. not sure if there is any alternative way?

like image 721
David.Chu.ca Avatar asked Dec 22 '09 18:12

David.Chu.ca


People also ask

How do you find the index of an array of elements?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.

How do I search an array in PowerShell?

Querying Arrays with PowerShell We can use the -in or -notin syntax to simply check if an array has a value that we pass to check.

How do I read an array in PowerShell?

You can also get the members of an array by typing a comma (,) before the value that is piped to the Get-Member cmdlet. The comma makes the array the second item in an array of arrays. PowerShell pipes the arrays one at a time and Get-Member returns the members of the array. Like the next two examples.


1 Answers

Use a for loop (or a foreach loop that iterates over the array index...same difference). I don't know of any system variable that holds the current array index inside a foreach loop, and I don't think one exists.

# example array
$array = "A", "B", "C"
$item = "B"
0..($array.Count - 1) | Where { $array[$_] -eq $item }
like image 162
Peter Seale Avatar answered Nov 10 '22 23:11

Peter Seale