Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 985
Chris Avatar asked Feb 05 '26 07:02

Chris


1 Answers

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.

like image 175
AdminOfThings Avatar answered Feb 06 '26 22:02

AdminOfThings



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!