Deep copying a PSObject

Note that here is a shorter, maybe a bit cleaner version of this (that I quite enjoy):

$data = Import-Csv .\test.csv

$serialData = [System.Management.Automation.PSSerializer]::Serialize($data)

$data2 = [System.Management.Automation.PSSerializer]::Deserialize($serialData)

Note:
However, weirdly, it does not keep the ordering of ordered hashtables.

$data = [ordered] @{
    1 = 1
    2 = 2
}

$serialData = [System.Management.Automation.PSSerializer]::Serialize($data)

$data2 = [System.Management.Automation.PSSerializer]::Deserialize($serialData)
$data2

Will output:

Name                           Value
----                           -----
2                              2
1                              1

While with other types it works just fine:

$data = [PsCustomObject] @{
    1 = 1
    2 = 2
}

$data = @(1, 2, 3)

Leave a Comment