Get index of current item in a PowerShell loop

前端 未结 5 1998
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-24 00:19

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\' }
         


        
5条回答
  •  独厮守ぢ
    2020-12-24 01:02

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

提交回复
热议问题