How do I add a column of incrementing values to cmdlet output?

南笙酒味 提交于 2019-11-30 18:20:22

问题


Suppose I call Get-Service and want to assign a new column ID with the cmdlet output that prints incrementing integers so that:

ID  Status Name                            DisplayName
--  ------ ----                            -----------
 0 Running AdobeARMservice                 Adobe Acrobat Update Service
 1 Stopped AeLookupSvc                     Application Experience
 2 Stopped ALG                             Application Layer Gateway Service

I'm trying to use Select-Object right now to add this column, but I don't quite understand how to iterate a variable in this sort of expression. Here's what I've got:

Get-Service |
Select-Object @{ Name = "ID" ; Expression= {  } }, Status, Name, DisplayName |
Format-Table -Autosize

Is there a way to iterate integers within Expression= { }, or am I going about this problem the wrong way?


回答1:


You can do it this way, though you will need to maintain some counter variable outside of the main expression.

$counter = 0
Get-Service |
Select-Object @{ Name = "ID" ; Expression= {$global:counter; $global:counter++} }, Status, Name, DisplayName |
Format-Table -Autosize

Another option, which is perhaps cleaner

Get-Service `
|% {$counter = -1} {$counter++; $_ | Add-Member -Name ID -Value $counter -MemberType NoteProperty -PassThru} `
| Format-Table ID



回答2:


I asked the same question a different way and got the following answer

$x = 10
Get-Service |
Select-Object @{ Name = "ID" ; Expression={ (([ref]$x).Value++) }}, Status, Name, DisplayName | Format-Table -Autosize

It wasn't at all clear to me that the expression is being invoked within Select-Object's scope, not the pipe's. The [ref] qualifier bumps the increment's result up to the pipe's scope achieving the same result as explicitly specifying the variable as global.



来源:https://stackoverflow.com/questions/18110377/how-do-i-add-a-column-of-incrementing-values-to-cmdlet-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!