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?
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.
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.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With