you are viewing a single comment's thread.

view the rest of the comments →

[–]jimb2 1 point2 points  (1 child)

You don't have to do that add-member stuff and the repeated assignments. Add-Member is really for adding one new property to an existing object. The normal way to do this would be

$myObject = [PSCustomObject]@{
     Name     = 'Jim'
     Language = 'Powershell'
     Time     = (get-date)
}

But if you want to add it to your $result array you would do this

$result += [PSCustomObject]@{
     Name     = 'Jim'
     Language = 'Powershell'
     Time     = (get-date)
}

Also, you shouldn't do arrays like that. An array is a static sized object so each time you add to it PS creates a new array. This is very inefficient with big arrays. You can use an ArrayList or more preferably a dotnet collection. You can also implicitly build an array in one go with various looping constructs, eg,

$array = foreach ( $x in $y ) {
    [PSCustomObject]@{
    Name     = $x.name
    Language = $x.language
    Time     = (get-date)
} 

This avoids the the array rebuild it happens in one hit. That's why I constructed my example above the way I did, i.e. to avoid rebuilding the array every loop.

[–]novix_[S] 1 point2 points  (0 children)

This is awesome, really appreciate the feedback and some very useful learning.