Search code examples
arrayspowershell

PowerShell copy an array completely


I'm trying to create a complete copy of an existing array. Every time I try this it doesn't seem to work. The thing is that I'm modifying the object names inside the new copied array, but they're also changed in the original array..

Simplified example

Function Get-Fruits {
    Param (
        $Fruits = @('Banana', 'Apple', 'Pear')
    )
    foreach ($F in $Fruits) {
        [PSCustomObject]@{
            Type = $F
        }
    }
}

$FruitsOriginal = Get-Fruits

Function Rename-ObjectName {
    # Copy the array here
    $FruitsNew = $FruitsOriginal # Not a true copy
    $FruitsNew = $FruitsOriginal | % {$_} # Not a true copy
    $FruitsNew = $FruitsOriginal.Clone() # Not a true copy

    $FruitsNew | Get-Member | ? MemberType -EQ NoteProperty | % {
    
        $Name = $_.Name

        $FruitsNew | % {
            $_ | Add-Member 'Tasty fruits' -NotePropertyValue $_.$Name
            $_.PSObject.Properties.Remove($Name)
        }
    }
}

Rename-ObjectName

The desired result is 2 completely separate arrays.

$FruitsOriginal

Type
----
Banana
Apple
Pear

$FruitsNew

Tasty fruits
------------
Banana
Apple
Pear

Thank you for your help.


Solution

  • You can use serialisation to deep clone your array:

    #Original data
    $FruitsOriginal = Get-Fruits
    
    # Serialize and Deserialize data using BinaryFormatter
    $ms = New-Object System.IO.MemoryStream
    $bf = New-Object System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
    $bf.Serialize($ms, $FruitsOriginal)
    $ms.Position = 0
    
    #Deep copied data
    $FruitsNew = $bf.Deserialize($ms)
    $ms.Close()