How to create new clone instance of PSObject object

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

    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
    

提交回复
热议问题