Search code examples
arrayspowershellvariablespscustomobject

Powershell: PSCustomObject array as parameter in function gets changed unexpectedly


In the simplified PS code below, I don't understand why the $MyPeople array gets changed after calling the changeData function. This array variable should just be made a copy of, and I expect the function to return another array variable into $UpdatedPeople and not touch $MyPeople:

function changeData {
    Param ([PSCustomObject[]]$people)
    $changed_people = $people
    $changed_people[0].Name = "NEW NAME"
    return $changed_people
}
# Original data:
$Person1 = [PSCustomObject]@{
    Name    = "First Person"
    ID      = 1
}
$Person2 = [PSCustomObject]@{
    Name    = "Second Person"
    ID      = 2
}
$MyPeople = $Person1,$Person2

"`$MyPeople[0] =`t`t" + $MyPeople[0]
"`n# Updating data..."
$UpdatedPeople  = changeData($MyPeople)
"`$UpdatedPeople[0] =`t" + $UpdatedPeople[0]
"`$MyPeople[0] =`t`t" + $MyPeople[0]

Console output:

$MyPeople[0] =          @{Name=First Person; ID=1}
# Updating data...
$UpdatedPeople[0] =     @{Name=NEW NAME; ID=1}
$MyPeople[0] =          @{Name=NEW NAME; ID=1}

Thanks!


Solution

  • PSObject2 = PSObject1 is not a copy but a reference. You need to clone or copy the original object using a method designed for that purpose.

    function changeData {
        Param ([PSCustomObject[]]$people)
        $changed_people = $people | Foreach-Object {$_.PSObject.Copy()}
        $changed_people[0].Name = "NEW NAME"
        return $changed_people
    }
    

    The technique above is simplistic and should work here. However, it is not a deep clone. So if your psobject properties contain other psobjects, you will need to look into doing a deep clone.