Pergunta

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?

Foi útil?

Solução

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

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top