0

Simple piece of code here ...

$array = @()
$numbers = 1..5
foreach ($number in $numbers) {
    $info = "" | select number,result,test
    $info.number = $number
    $info.result = $number.ToString() + "-result"
    $array+=$info
    $info
}

[System.Collections.ArrayList]$arraylist = $array
$arraylist[0].test = "true"

However, whenever I modify $arraylist[0] above it also modifies $array[0]

PS C:\Users\testuser> $array[0]

number result   test
------ ------   ----
     1 1-result true

PS C:\Users\testuser> $arraylist[0]

number result   test
------ ------   ----
     1 1-result true

How can I stop this from happening? I want to keep the original array intact and only modify the ArrayList?

J.D.
  • 1
  • 1
  • 1
  • The right way to do this is to make a deep clone of your array. It is simple in theory but not as easy to code. You can try `[System.Collections.ArrayList]$arraylist = @($array | select *)` but you will still have a reference to `$info`’s object that gets updated. – AdminOfThings Jan 15 '20 at 03:49
  • As @AdminOfThings said, you need a new copy of your original array. Here's a similar question: https://stackoverflow.com/questions/29699026/powershell-copy-an-array-completely – Glenn Jan 15 '20 at 03:53
  • @AdminOfThings - the code you have above works :) `[System.Collections.ArrayList]$arraylist = @($array | select *)` THANK YOU! – J.D. Jan 15 '20 at 04:08

0 Answers0