3

在下面的简化 PS 代码中,我不明白为什么在调用函数$MyPeople后数组会发生变化。changeData这个数组变量应该只是一个副本,我希望该函数将另一个数组变量返回到$UpdatedPeople而不是 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]

控制台输出:

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

谢谢!

4

2 回答 2

2

PSObject2 = PSObject1不是副本,而是参考。您需要使用为此目的设计的方法克隆或复制原始对象。

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

上面的技术很简单,应该在这里工作。但是,它不是深度克隆。因此,如果您的 psobject 属性包含其他 psobject,您将需要考虑进行深度克隆。

于 2020-03-30T15:56:57.070 回答
1

我们可以克隆 PSCustomObject。我们将创建一个新的 PSObject 并通过作为参数给出的 psobject 进行枚举,并将它们一一添加到浅拷贝中。

function changeData {
    Param ([PSCustomObject[]]$people)
    $changed_people = New-Object PSobject -Property @{}
    $people.psobject.properties | ForEach {
      $changed_people | Add-Member -MemberType $_.MemberType -Name $_.Name -Value $_.Value
    }
    $changed_people[0].Name = 'NEW NAME'
    return $changed_people
}

或者通过@AdminOfThings 使用另一种方法

于 2020-03-30T16:10:43.280 回答