Get array index inside forsach Powershell loop?

I have a loop that uses the foreach keyword:

foreach ($ln in Get-Content "c:\ATextFile.txt" ) 

Is it possible to find out the index of the array referenced by $ ln during the iteration? Or do I need to create and increase a separate count variable for each iteration of the loop?

+4
source share
2 answers

Yes, use a for loop (something like (gc c:\ATextFile.txt).count will be the upper limit) or an external counter.

A related answer (for C #, but basically both use the same enumerated concepts): How do you get the index of the current iteration of the foreach loop?

+3
source

Get-Content also adds ReadCount NoteProperty with the current line number.

 Get-Content foo.txt | foreach { '{0} {1}' -f $_.ReadCount, $_ } 
+2
source

Source: https://habr.com/ru/post/1368873/


All Articles