Powershell – Appending to an array within a ForEach-Object loop

powershellscripting

I've run into a strange problem when attempting to append to an array from within a ForEach-Object loop that is traversing another array.

I have attempted to recreate the problem as concisely as I can:

$InputObject1 = @{
    Property = '123456';
}

$InputObject2 = @{
    Property = '654321';
}

$InputArray = $InputObject1, $InputObject2


$OutputObject = @{
    TargetArray = '';
} 

$InputArray | ForEach-Object {
    Write-Output $_.property
    $OutputObject.TargetArray += $_.property
}

Write-Output "Testing Array Readback" 
Write-Output $OutputObject.TargetArray[0]
Write-Output $OutputObject.TargetArray[1]

The output I get is:

123456
654321
TESTING Array Readback
1
2

However, the output I'm trying to achieve is:

123456
654321
TESTING Array Readback
123456
654321

For some reason, even though the value of $_.property is different in each iteration of the loop; The value that is written to the $OutputObject.TargetArray almost appears to be traversing the value of the first iteration in some strange recursive manner.

I'm still quite new to PowerShell scripting so my apologies if I've made a really obvious mistake or assumption somewhere. This one has completely stumped me. Thanks in advance!


EDIT: Solution found.

Thanks to the input from @LotPings, I figured out what the problem was. My definition of TargetArray within $OutputObject was incorrect.

I had incorrectly written:

$OutputObject = @{
    TargetArray = '';
}

Which means the line:

$OutputObject.TargetArray += $_.property

… is actually concatenating the two values together resulting in '123456654321'. As opposed to adding a value to the array like {123456, 654321}.

The $OutputObject Hash Table should therefore be defined as:

$OutputObject = @{
    TargetArray = @();
}

This results in the desired output.

Best Answer

$InputArray and $OutputObject are both hashtables,
look what they contain:

> $InputArray

Name                           Value
----                           -----
Property                       123456
Property                       654321

> $OutputObject

Name                           Value
----                           -----
TargetArray                    123456654321

And think about how this could happen.