title: Powershell values within a loop losing their value
body: <p>Forgive the title, I'm not really sure how to explain what I'm seeing.</p>
  
  <p>Sample Code:    </p>
  
  <pre><code>    $SampleValues = 1..5
      $Result = "" | Select ID
      $Results = @()  
  
      $SampleValues | %{
          $Result.ID = $_
          $Results += $Result
      }
  
  $Results
  </code></pre>
  
  <p>This is fairly straightforward:</p>
  
  <ul>
  <li>Create an array with 5 numbers to be used in a loop</li>
  <li>Create a temp variable with a NoteProperty called ID</li>
  <li>Create an empty array to store results</li>
  <li>Iterate through each of the 5 numbers assigning them to a temp variable then appending that to an array.</li>
  </ul>
  
  <p>The expected result is 1,2,3,4,5 but when run this returns 5,5,5,5,5</p>
  
  <p>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.</p>
  
  <p>The only solution I've found is the following, which moves the $Result declaration into the loop. </p>
  
  <pre><code>    $SampleValues = 1..5
      $Results = @()
  
  $SampleValues | %{
      $Result = "" | Select ID
      $Result.ID = $_
      $Results += $Result
      }
  </code></pre>
  
  <p>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.</p>
  
  <p>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.</p>