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
If you're copying an array of objects/value that contains all "truthy" values, or you want to quickly filter out null and "falsey" values, then this works great:
$FruitsNew = $FruitsOriginal|?{$_}
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
Depending on what you need to do with the objects, and if they're simple enough (as in your example), you could just replace them with a new object.
$NewFruits = $FruitsOriginal | %{ [PSCustomObject]@{ "Tasty Fruits" = $_.Type } }
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.