Search code examples
powershellpowershell-cmdlet

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


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?


Solution

  • 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