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

2023-12-10

假设我打电话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

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

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

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


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

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

另一种选择,也许更干净

Get-Service `
|% {$counter = -1} {$counter++; $_ | Add-Member -Name ID -Value $counter -MemberType NoteProperty -PassThru} `
| Format-Table ID
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何向 cmdlet 输出添加一列递增值? 的相关文章

随机推荐