Josef Nemec Josef Nemec - 1 year ago 416
PowerShell Question

How to create new clone instance of PSObject object

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?

Answer Source

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
$ | % {
    $o2 | Add-Member -MemberType $_.MemberType -Name $_.Name -Value $_.Value
$o.prop1 = 'newvalue'



prop2     prop1                                                                 
-----     -----                                                                 
b         newvalue                                                              
b         a      
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download