5

I have a loop that uses the foreach keyword:

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

Is it possible to find out the array index referred to by $ln during the iteration? Or do I need to create and increment a separate counting variable for each loop iteration?

2 Answers 2

4

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

Get-Content foo.txt  | foreach { '{0} {1}' -f $_.ReadCount, $_ }
Sign up to request clarification or add additional context in comments.

Comments

3

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.