Powershell - Normal variables are behaving like reference variables

Viewed 34

Here is the simple powershell code -

$arr = @()
$a = [PSCustomObject]@{
    a = 'a'
    b = 'b'
}
$arr += $a
$b = [PSCustomObject]@{
    a = 'c'
    b = 'd'
}
$arr += $b

$f = $arr | Where-Object {$_.a -eq 'a'}
$f.a = '1'
Write-Host "`$a.a=$($a.a); `$f.a=$($f.a)"
$f.a = '11'
Write-Host "`$a.a=$($a.a); `$f.a=$($f.a)"

Output:

$a.a=1; $f.a=1
$a.a=11; $f.a=11

My problem is - How the changing of $f value is also changing the value of $a value? I'm not aware of this concept.

And, what can I do to avoid this behavior?

1 Answers

Type [PSCustomObject] is a reference type, so multiple variables can "point to" (reference) a given instance; see this answer for more information about reference types vs. value types.

If you want to create a copy (a shallow clone) of a [PSCustomObject] instance, call .psobject.Copy():

$f = ($arr | Where-Object {$_.a -eq 'a'}).psobject.Copy()
Related