Share via

Question about PSCustomObject

Martin Daganzo, Jorge 21 Reputation points
2022-05-25T18:19:26.733+00:00

Hi everyone!

I have this example and I don't understand why $a gets "TEST3"

Can someone clarify it for me?

$a = @()
$b = @()

$a = New-Object PsObject -Property @{ TEST = "AA" }
$a | Add-Member -Name 'TEST2' -Type NoteProperty -Value "AA"
$a

$b = $a
$b | Add-Member -Name 'TEST3' -Type NoteProperty -Value "AA"

$a

Thanks!

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments

Answer accepted by question author

Michael Taylor 61,226 Reputation points
2022-05-25T18:33:55.813+00:00

Because $a and $b refer to the same object. In this particular case you are creating a dynamic object in memory when you use New-Object. You then assign to the variable $a that object. You can now access the object using $a. A little while later you assign $a to $b. You now have 2 variables referring to the same object in memory. Any changes you make to one variable's object will be seen by the other because they both refer to the same object. This is formally known as reference semantics and is a consequence of PS using .NET to work with these objects.

Note that this only applies to non-primitive types and a few others. For example numbers, strings and date-time values do not follow reference semantics and behave how you might expect.

$x = 10
$y = $x

In the above example $x and $y both have a copy of the same value but are otherwise independent. If you know the underlying type of the value then you can determine if it follows value or reference semantics by looking at the type definition.

$a.GetType().IsValueType

Except for perhaps strings and arrays, if it is a value type then it follows value semantics otherwise it follows reference semantics.

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.