在 PowerShell 循环中获取当前项目的索引 [英] Get index of current item in a PowerShell loop
本文介绍了在 PowerShell 循环中获取当前项目的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定 PowerShell 中的项目列表,如何从循环中找到当前项目的索引?
Given a list of items in PowerShell, how do I find the index of the current item from within a loop?
例如:
$letters = { 'A', 'B', 'C' }
$letters | % {
# Can I easily get the index of $_ here?
}
所有这一切的目标是我想使用 Format-Table 并添加一个带有当前项索引的初始列.通过这种方式,人们可以交互地选择要选择的项目.
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.
推荐答案
我不确定自动"变量是否可行.你总是可以为自己声明一个并增加它:
I am not sure it's possible with an "automatic" variable. You can always declare one for yourself and increment it:
$letters = { 'A', 'B', 'C' }
$letters | % {$counter = 0}{...;$counter++}
或者使用 for
循环代替...
Or use a for
loop instead...
for ($counter=0; $counter -lt $letters.Length; $counter++){...}
这篇关于在 PowerShell 循环中获取当前项目的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文