Forgive the title, I'm not really sure how to explain what I'm seeing.
Sample Code:
$SampleValues = 1..5
$Result = "" | Select ID
$Results = @()
$SampleValues | %{
$Result.ID = $_
$Results += $Result
}
$Results
This is fairly straightforward:
- Create an array with 5 numbers to be used in a loop
- Create a temp variable with a NoteProperty called ID
- Create an empty array to store results
- Iterate through each of the 5 numbers assigning them to a temp variable then appending that to an array.
The expected result is 1,2,3,4,5 but when run this returns 5,5,5,5,5
This is a barebones example taken from a much more complex script and I'm trying to figure out why the result is what it is. In each iteration all elements that have already been added to $Results have their values updated to the most recent value. I've tested forcing everything to $Script: or $Global: scope and get the same results.
The only solution I've found is the following, which moves the $Result declaration into the loop.
$SampleValues = 1..5
$Results = @()
$SampleValues | %{
$Result = "" | Select ID
$Result.ID = $_
$Results += $Result
}
This works (you get 1,2,3,4,5 as your results). It looks like $Results is just holding multiple references to a singular $Result object but why does moving this into the loop fix the problem? In this example $Result is a string so perhaps it is creating a new object each iteration but even when I forced $Result to be an integer (which shouldn't recreate a new object since an integer isn't immutable like a string) it still fixed the problem and I got the result I expected.
If anybody has any insight into exactly why this fixes the problem I've be very curious. There are plenty of alternatives for me to implement but not understanding specifically why this works this way is bugging me.