Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of current item in a PowerShell loop

Tags:

powershell

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.

like image 375
Brian Vallelunga Avatar asked Nov 23 '09 19:11

Brian Vallelunga


People also ask

How do I get the first element of an array in PowerShell?

Windows PowerShell arrays are zero-based, so to refer to the first element of the array $var3 (“element zero”), you would write $var3 [0].

What is @() in PowerShell script?

What is @() in PowerShell Script? In PowerShell, the array subexpression operator “@()” is used to create an array. To do that, the array sub-expression operator takes the statements within the parentheses and produces the array of objects depending upon the statements specified in it.

What does $_ mean in PowerShell?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.


1 Answers

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

like image 94
Keith Hill Avatar answered Oct 03 '22 12:10

Keith Hill