I want to create new instance of my custom PSObject. I have a Button object created as PSObject and I want to create new object Button2 which has the same members as Button does, but I can't find a way how to clone the original object without making it referenced in original object (if I change a property in Button2 it changes in Button as well). Is there a way how to do it similarly as with hashtables and arrays via some Clone() method?
New-Object creates the object and sets each property value and invokes each method in the order that they appear in the hash table. If the new object is derived from the PSObject class, a property is specified that does not exist on the object, it will be added to the object as a NoteProperty.
A NoteProperty is a static property name, often added by Select-Object or Add-Member . Finally, you might also see PropertySet . Think of this as a prepackaged bundle of properties. These are defined by PowerShell or cmdlet developers—for example, a process object as a PSResources property set.
Long description. The [pscustomobject] type accelerator was added in PowerShell 4.0. Prior to adding this type accelerator, creating an object with member properties and values was more complicated. Originally, you had to use New-Object to create the object and Add-Member to add properties.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With