How to create new clone instance of PSObject object

前端 未结 9 662
野趣味
野趣味 2020-12-09 02:20

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

相关标签:
9条回答
  • 2020-12-09 02:59

    Put this in a Utility class or define it in your current section

    function clone($obj)
    {
        $newobj = New-Object PsObject
        $obj.psobject.Properties | % {Add-Member -MemberType NoteProperty -InputObject $newobj -Name $_.Name -Value $_.Value}
        return $newobj
    }
    

    Usage:

    $clonedobj = clone $obj

    0 讨论(0)
  • 2020-12-09 03:05

    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
    
    0 讨论(0)
  • 2020-12-09 03:07

    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      
    
    0 讨论(0)
  • 2020-12-09 03:07

    The Better way i found out was to use ConvertTo-Json and ConvertFrom-Json. Ee - Suppose you want to clone a object $toBeClonedObject, just run below code to clone.

    $clonedObject = $toBeClonedObject | ConvertTo-Json | ConvertFrom-Json
    
    0 讨论(0)
  • 2020-12-09 03:08

    Another possibility:

     $o1 = New-Object PsObject -Property @{ prop1='a' ; prop2='b' }
     $o2 = $o1 | select *
     $o2.prop1 = 'newvalue'
     $o1.prop1
     $o2.prop1
     a
     newvalue
    
    0 讨论(0)
  • 2020-12-09 03:09

    Here's a [pscustomobject] example with the hidden .psobject.copy():

    $a = [pscustomobject]@{message='hi'}
    $a.message
    hi
    
    $b = $a.psobject.copy()
    $b.message
    hi
    
    $a.message = 'there'
    $a.message
    there
    
    $b.message
    hi
    
    0 讨论(0)
提交回复
热议问题