Question about Objects and Variables

Welcome Forums General PowerShell Q&A Question about Objects and Variables

This topic contains 4 replies, has 4 voices, and was last updated by

2 years, 3 months ago.

  • Author
  • #52675

    Points: 0
    Rank: Member

    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?



  • #52678

    Points: 0
    Rank: Member

    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()
  • #52684

    Points: 355
    Helping Hand
    Rank: Contributor

    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.

  • #52718

    Points: 0
    Rank: Member

    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.

  • #52752

    Points: 0
    Rank: Member

    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.

The topic ‘Question about Objects and Variables’ is closed to new replies.