Get index of current item in a PowerShell loop

Viewed 154735

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.

5 Answers

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

Related