如何向cmdlet输出添加一列递增值?

Ant*_*ace 3 powershell cmdlets

假设我调用Get-Service并希望ID使用cmdlet输出分配一个新列,该输出打印递增的整数,以便:

ID  Status Name                            DisplayName
--  ------ ----                            -----------
 0 Running AdobeARMservice                 Adobe Acrobat Update Service
 1 Stopped AeLookupSvc                     Application Experience
 2 Stopped ALG                             Application Layer Gateway Service
Run Code Online (Sandbox Code Playgroud)

我现在正试图Select-Object添加此列,但我不太明白如何在这种表达式中迭代变量.这是我得到的:

Get-Service |
Select-Object @{ Name = "ID" ; Expression= {  } }, Status, Name, DisplayName |
Format-Table -Autosize
Run Code Online (Sandbox Code Playgroud)

有没有办法迭代整数Expression= { },或者我是否以错误的方式解决这个问题?

lat*_*kin 8

您可以这样做,但您需要在主表达式之外维护一些计数器变量.

$counter = 0
Get-Service |
Select-Object @{ Name = "ID" ; Expression= {$global:counter; $global:counter++} }, Status, Name, DisplayName |
Format-Table -Autosize
Run Code Online (Sandbox Code Playgroud)

另一个选择,也许更清洁

Get-Service `
|% {$counter = -1} {$counter++; $_ | Add-Member -Name ID -Value $counter -MemberType NoteProperty -PassThru} `
| Format-Table ID
Run Code Online (Sandbox Code Playgroud)