在 PowerShell 循环中获取当前项的索引

给定 PowerShell 中的项列表,如何在循环中查找当前项的索引?

例如:

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


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

所有这些操作的目标是使用 格式-表格输出一个集合,并添加一个带有当前项索引的初始列。这样人们就可以交互式地选择要选择的项目。

158917 次浏览

I am 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++){...}

.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.

0..($letters.count-1) | foreach { "Value: {0}, Index: {1}" -f $letters[$_],$_}

For PowerShell 3.0 and later, there is one built in :)

foreach ($item in $array) {
$array.IndexOf($item)
}

For those coming here from Google like I did, later versions of Powershell have a $foreach automatic variable. You can find the "current" object with $foreach.Current

I found Cédric Rup's answer very helpful but if (like me) you are confused by the '%' syntax/alias, here it is expanded out:

$letters = { 'A', 'B', 'C' }
$letters | ForEach-Object -Begin {$counter = 0} -Process {...;$counter++}