Powershell values ​​inside a loop lose their value

Sorry for the title, I'm not quite sure how to explain what I see.

Code example:

    $SampleValues = 1..5
    $Result = "" | Select ID
    $Results = @()  

    $SampleValues | %{
        $Result.ID = $_
        $Results += $Result
    }

$Results

It is pretty simple:

  • Create an array with 5 numbers to be used in a loop
  • Create a temporary variable using NoteProperty named ID
  • Create an empty array to store the results
  • Swipe through each of the 5 numbers, assigning them a temporary variable, and then adding it to the array.

The expected result is 1,2,3,4,5, but at startup it returns 5,5,5,5,5

, script, , , . , $Results, , . , $Script: $Global: scope .

- , $Result .

    $SampleValues = 1..5
    $Results = @()

$SampleValues | %{
    $Result = "" | Select ID
    $Result.ID = $_
    $Results += $Result
    }

( 1,2,3,4,5 ). , $Results $Result, ? $Result , , , , $Result ( , , ) , .

- , , . , , , .

+3
2

, , $Result, (5 ).

, "" | Select ID 123 | Select ID, PSCustomObject, - , .

, Powershell - .NET . #, , Powershell , 5s (, #):

var SampleValues = new []{1,2,3,4,5};
var Result = new CustomObject(){ ID = "" };
var Results = new List<Object>();

foreach (var _ in SampleValues) {
    Result.ID = _;
    Results.Add(Result);
}

, , var Result = new CustomObject(){ ID = "" } foreach , Powershell .

+8

$Result , , , , $Result ( , , ) , .

, $ . (ID), .

Powershell - . , . addind $result to $results 5 5 $result, 5 .

$result.id(/ ) $results $result, :

 $SampleValues = 1..5
     $Result = "" | Select ID
     $Results = @()  

     $SampleValues | %{
         $Result.ID = $_
         $Results += $Result.ID
     }

 1
 2
 3
 4
 5
+1
source

All Articles