在Powershell foreach循环中检索数组索引?

时间:2011-08-24 22:28:51

标签: powershell

我有一个使用foreach关键字的循环:

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

是否有可能在迭代期间找出$ ln引用的数组索引?或者我是否需要为每个循环迭代创建和增加一个单独的计数变量?

2 个答案:

答案 0 :(得分:3)

是的,要么使用for循环(类似(gc c:\ATextFile.txt).count将是上限),要么使用外部计数器。

相关答案(对于C#,但基本上都使用相同的可枚举概念):How do you get the index of the current iteration of a foreach loop?

答案 1 :(得分:2)

Get-Content还会添加一个包含当前行号的ReadCount NoteProperty。

Get-Content foo.txt  | foreach { '{0} {1}' -f $_.ReadCount, $_ }
相关问题