Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create new clone instance of PSObject object

Tags:

powershell

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?

like image 482
Josef Nemec Avatar asked Mar 06 '12 10:03

Josef Nemec


People also ask

What is new object PSObject?

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.

What is NoteProperty in PowerShell?

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.

What is a PSCustomObject?

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.


2 Answers

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 
like image 108
Woody Avatar answered Sep 28 '22 23:09

Woody


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 
like image 34
TeraFlux Avatar answered Sep 29 '22 01:09

TeraFlux