How to create new clone instance of PSObject object

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

    Starting from PowerShell v5, you can use Class. The problem with psobject.Copy() is, if you update the cloned object, then your template object's referenced properties will be also updated.

    example:

    function testTemplates
    {
        $PSCustomObjectTemplate = New-Object PSCustomObject -Property @{
            List1 = [System.Collections.Generic.List[string]]@()  # will be updated in template
            String1 = "value1" # will not be updated in template
            Bool1 = $false # will not be updated in template
        }
    
        $objectFromPSTemplate1 = $PSCustomObjectTemplate.psobject.Copy()
        $objectFromPSTemplate1.List1.Add("Value")
        $objectFromPSTemplate1.String1 = "value2" 
        $objectFromPSTemplate.Bool1 = $true 
    
        # $PSCustomObjectTemplate IS updated, so CANNOT be used as a clean template!
        $PSCustomObjectTemplate
    
        Class ClassTemplate {
            [System.Collections.Generic.List[string]]$List1 = @() # will not be updated in template
            [string]$String1 = "value1" # will not be updated in template
            [bool]$Bool1 = $false # will not be updated in template
        }
        $objectFromClassTemplate = [ClassTemplate]::new()
        $objectFromClassTemplate.List1.Add("Value")
        $objectFromClassTemplate.String1 = "value2"
        $objectFromClassTemplate.Bool1 = $true
    
        # $ClassTemplate IS NOT updated, so can be used as a clean template!
        [ClassTemplate]::new()
    }
    

    testTemplates

    PS C:\Windows\system32> testTemplates
    
    List1   String1 Bool1
    -----   ------- -----
    {Value} value1  False       
    

    -> Template from PSCustomObject is updated (referenced property -List1)

    List1   String1 Bool1
    -----   ------- -----
    {}      value1  False       
    

    -> Template from Class is safe

提交回复
热议问题