如何向 cmdlet 输出添加一列递增值? [英] How do I add a column of incrementing values to cmdlet output?

查看:44
本文介绍了如何向 cmdlet 输出添加一列递增值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我正在尝试使用 Select-Object 现在添加此列,但我不太明白如何在此类表达式中迭代变量.这是我所拥有的:

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

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

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

推荐答案

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

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

这篇关于如何向 cmdlet 输出添加一列递增值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆