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?

1
  • 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) Commented May 15, 2020 at 7:41

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.