How to create new clone instance of PSObject object

前端 未结 9 684
野趣味
野趣味 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 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      
    

提交回复
热议问题