Powershell: Add objects to an array of objects

arrays, powershell, scripting

Solution

To append to an array, just use the `+=` operator.

`$Target += $TargetObject`

Also, you need to declare `$Target = @()` before your loop because otherwise, it will empty the array every loop.

Problem

I have this script where I want to add an object to an array called `$Target` in every foreach. ``` foreach ($Machine in $Machines) { $TargetProperties = @{Name=$Machine} $TargetObject = New-Object PSObject –Property $TargetProperties $Target= @() $Target = $TargetObject } ``` I know it is not working because `$Target = $TargetObject` makes it equal to the same object. How can I append to the array instead of replace?

Original source