Reputation: 26023
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?
Upvotes: 4
Views: 5949
Reputation: 157
This function keeps your code clean:
$table | Add-Increment -label "MyIndex"
function Add-Increment([string]$label="Index") {
begin {
$index = 0
}
process {
$_ | select @{l=$label; e={ $index }}, *
$index++ | Out-Null
}
}
Upvotes: 0
Reputation: 746
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.
Upvotes: 2
Reputation: 16792
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
Upvotes: 10