Get index of current item in a PowerShell loop

前端 未结 5 2002
爱一瞬间的悲伤
爱一瞬间的悲伤 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 00:49

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

提交回复
热议问题