PowerShell copy an array completely
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()
# Copy the array here
$FruitsCopy = @()
$FruitsCopy = $FruitsCopy + $FruitsOriginal
Since Powershell 3.0, same approach as Jaco's answer but using PSSerializer.
It uses a CliXML
format compatible with Export-Clixml
& Import-Clixml
and personally I find it easier to read.
In theory, supports a nested hierarchy up to [int32]::MaxValue
levels-deep
# Original data
$FruitsOriginal = Get-Fruits
# Serialize and Deserialize data using PSSerializer:
$_TempCliXMLString = [System.Management.Automation.PSSerializer]::Serialize($FruitsOriginal, [int32]::MaxValue)
$FruitsNew = [System.Management.Automation.PSSerializer]::Deserialize($_TempCliXMLString)
# Deep copy done.