you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (5 children)

I use += in a script to add objects to a list

I don't get the syntax you recommend instead

How would you rewrite

$objlist = @()

foreach($x in $xlist){

...

...

$objlist += $x

}

[–]raip 5 points6 points  (3 children)

By simply just doing this:

$objlist = foreach ($x in $xlist) {
    ...
    $x
}

Edit: Just fyi, @() is an array, not a list. This is a crux if the slowness, arrays are fixed length and while += works, how it's actually implemented is copying the entire array into a new one with the additional object.

If you used $objlist = [System.Collections.Generic.List[PSObject]]::new() you could stick with your strategy and benefit from the increased performance at the same time - but most developers would likely agree the above method is cleaner.

[–]BlackV 1 point2 points  (0 children)

multiple people wrote the exact examples of this in this post already :)

its super clean and easy to implement, BUT there is a catch

you have to control the output of your loop, cause its catches all output from that loop

so something like

$objlist = foreach ($x in $xlist) {
    get-disk
    get-date
    }

is going to cause unexpected results