How to create new clone instance of PSObject object

Another possibility:

 $o1 = New-Object PsObject -Property @{ prop1='a' ; prop2='b' }
 $o2 = $o1 | select *
 $o2.prop1 = 'newvalue'
 $o1.prop1
 $o2.prop1
 a
 newvalue

Indeed there is no clone method! However where there is a will...

$o = New-Object PsObject -Property @{ prop1='a' ; prop2='b' }
$o2 = New-Object PsObject
$o.psobject.properties | % {
    $o2 | Add-Member -MemberType $_.MemberType -Name $_.Name -Value $_.Value
}
$o.prop1 = 'newvalue'

$o
$o2

Output:

prop2     prop1                                                                 
-----     -----                                                                 
b         newvalue                                                              
b         a      

Easiest way is to use the Copy Method of a PsObject ==> $o2 = $o1.PsObject.Copy()

$o1 = New-Object -TypeName PsObject -Property @{
    Fld1 = 'Fld1';
    Fld2 = 'Fld2';
    Fld3 = 'Fld3'}

$o2 = $o1.PsObject.Copy()

$o2 | Add-Member -MemberType NoteProperty -Name Fld4 -Value 'Fld4'
$o2.Fld1 = 'Changed_Fld'

$o1 | Format-List
$o2 | Format-List

Output:

Fld3 : Fld3
Fld2 : Fld2
Fld1 : Fld1

Fld3 : Fld3
Fld2 : Fld2
Fld1 : Changed_Fld
Fld4 : Fld4

For some reason PSObject.Copy() doesn't work for all object types. Another solution to create a copy of an object is to convert it to/from Json then save it in a new variable:

$CustomObject1 = [pscustomobject]@{a=1; b=2; c=3; d=4}
$CustomObject2 = $CustomObject1 | ConvertTo-Json -depth 100 | ConvertFrom-Json
$CustomObject2 | add-Member -Name "e" -Value "5" -MemberType noteproperty

$CustomObject1 | Format-List
$CustomObject2 | Format-List

Tags:

Powershell