Question about Objects and Variables

So, I was playing around trying to think of a better way of writing a script of mine. I came across this oddity:

$Obj1 = New-Object PSCustomObject @{test = $env:COMPUTERNAME}
$Obj2 = $Obj1

$Obj2 | Add-Member -Name SomeData -MemberType NoteProperty -Value "Some Data"


I would never use this in production, but I just want to understand how it updates both objects, should they not be separate objects?



A variable is a pointer to a location in memory. Assigning a variable an object doesn’t create a copy of the object in memory, it just sets the memory location. If you want an actual copy:

$b = $a.psobject.copy()

Some other notes. You are creating a hash table versus an object in your example. It appears to be a mesh of several custom object methods.

PS C:\Users\Rob> $Obj1

Name                           Value                                                                                                                                                                        
----                           -----                                                                                                                                                                        
test                           ROB-PC                                                                                                                                                                       

You object creation should look more like this.

$obj1 = @()
$obj1 += New-Object -TypeName PSObject -Property @{test = $env:COMPUTERNAME}
$obj1 += [pscustomobject]@{test="Computer123"}

It was interesting that Add-Member was still adding a property note to a hash table. Another simple way to make a copy is to use Select which will generate a new PSObject with the properties you specify. So, Select * or Select Name would generate a new object to work with.

Ah that makes sense its a pointer to a memory location, hence why it updates it regardless of which variable you use.

To be honest, its not something I would ever do I was just playing around. If anything I would create a class and use that.

The Technet page for Set-DNSServerResourceRecord uses this as an example of creating 2 independent objects with the same command, which is later pointed out in the comments as inaccurate.