Sure, that can be done. If you want to sort the output, though, you’ll wind up holding the entire result set in memory temporarily, which may cause an OutOfMemory error.
Here’s a basic example of adding a “Number” property to objects in the pipeline:
I try to spread love and understanding about powershell anywhere and any time. Every time I start using Add-Member, people either love it(about 10%) or ask me if there is another way. In my bag of tricks I usually pull something like this out:
The only reason I would choose that approach (several extra lines of code, not quite as easily read) is if it performed significantly better, and I wanted to optimize the code to perform well over a large data set. Based on my tests just now, though, it actualy took about 3 times as long to use the Select-Object approach.
yes, I know there is a performance hit. That was not the point. Sure, I have “several” extra lines of code, however my code example with the same select you have, is actually 36 characters less to type I was wondering what people are using to solve these kind of problems, what approach they find easy to understand and relate to.
I didn’t use aliases or positional parameters in my example the way you did with Select-Object, and I also used PowerShell 2.0-compatible syntax. If character count matters, that line could be written like this in version 3.0 or later:
$_ | Add-Member Number (++$index) -pa
Personally, I prefer to use the full syntax, for code clarity and all.
You can add the -AutoSize switch when calling Format-Table to address that. Like sorting the list, this requires that the entire result set be temporarily held in memory, but since you’re already doing that, that’s not a big deal.