2

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?

ShitalSavekar
  • 379
  • 2
  • 4
  • 10
  • Usually **objects** are referenced. One of the reasons for this is that the size of an object is undefined as in comparison to a primitive where the size is fixed. This is quiet common for any programming language, see: [Reference (computer science)](https://en.m.wikipedia.org/wiki/Reference_(computer_science)) – iRon May 15 '20 at 07:41

1 Answers1

4

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()
mklement0
  • 382,024
  • 64
  • 607
  • 775