public
Created

PowerShell Deepcopy demo

  • Download Gist
DeepCopyTest.ps1
PowerShell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
# Get original data
$data = @{
First = 'Justin';
Last = 'Dearing';
Resume = @{
Experience = [HashTable[]]@(
@{
StartDate = [DateTime] (Get-Date '2002-03-23');
EndDate = [DateTime] (Get-Date '2007-05-15');
Company = 'ACME ISP';
Title = 'Support Technician';
};
@{
StartDate = [DateTime] (Get-Date '2007-05-16');
EndDate = [DateTime] (Get-Date)
Company = 'Innitech';
Title = 'Developer';
};
)
};
}
 
Write-Host
Write-Host $data.GetType().FullName
Write-Host "Shallow Copy"
 
$dataShallow = $data.Clone();
$dataShallow.Resume.Experience[1].Title = 'Senior Developer';
$data.Resume.Experience |%{ New-Object PSObject -Property $_ }
 
 
# Serialize and Deserialize data using BinaryFormatter
$ms = New-Object System.IO.MemoryStream
$bf = New-Object System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
$bf.Serialize($ms, $data)
$ms.Position = 0
$dataDeep = $bf.Deserialize($ms)
$ms.Close()
 
$dataDeep.Resume.Experience[1].Title = 'Junior Developer';
Write-Host "Deep Copy Original"
$data.Resume.Experience |%{ New-Object PSObject -Property $_ }
Write-Host "Deep Copy"
$dataDeep.Resume.Experience |%{ New-Object PSObject -Property $_ }

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.