Reputation: 71
I wish to list the index of an item in a result table.
In this case I am using get-aduser with the filter option.
I am then using format-table with -Property to display only the properties I want.
I previously used a loop to display the items along with a counter to emulate the index but this was messy and I wanted it in a table.
Code:
$search_param = read-host "Enter search string: "
$search_param = "*" + $search_param + "*" # Construct search param.
$search_result = Get-ADUser -Filter {Surname -like $search_param -or GivenName -like $search_param -or SamAccountName -like $search_param}
$search_result | format-table -Property GivenName,Surname,SamAccountName
How can I get format-table to display the item index/position without using some kind of loop? ie, is there some kind of 'hidden' index property that I can simply provide to format-table?
Upvotes: 3
Views: 7987
Reputation: 428
The ForEach-Object
cmdlet can be used to create a calculated "index" property for the Format-Table
cmdlet
For Example:
$search_result | ForEach-Object {$index=0} {$_; $index++} | Format-Table -Property @{ Label="index";Expression={$index}; Width=5 },GivenName,Surname,SamAccountName
Additional References:
Adding Array Index Numbers to PowerShell Custom Objects
Upvotes: 5
Reputation: 376
$procs = Get-Process
#option 1
$procs | Select @{N='Index'; E={$procs.IndexOf($_)}}, name, handles
#option 2
$procs | Format-Table -Property @{name="index";expression={$procs.IndexOf($_)}},name,handles
Upvotes: 0
Reputation: 72670
The format-table
CmdLet -Property
param can be a new calculated property see Format-table help.
Here is an example with a computed index on Get-Process objects.
$index=0
Get-Process | Format-Table -Property @{name="index";expression={$global:index;$global:index+=1}},name,handles
Upvotes: 2
Reputation: 126892
In my opinion you can't, you need to extend the objects with an Index property and include it in your Format-Table
command.
Upvotes: -1