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?
This question is related to
arrays
powershell
scripting
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.
Source: Stackoverflow.com