0

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.

  • The output hashtable should be defined as @{ TargetArray = $InputArray.Property } and no loop. Any time you see += in PowerShell you should think "this is a bad way to do it, it's taking more code and running more slowly" } – TessellatingHeckler May 4 '18 at 0:30
2

$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.

  • Thanks for the information. I see where the mistake is now. I needed to define TargetArray using @() to indicate it was an empty array as opposed to setting it to a blank value. I'll edit the post to include the corrected script. Thanks again! – Brother Kaif May 3 '18 at 16:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.