PSCustomObjects - Understanding the difference

Hi everyone,

I just did a little exercise to help me understand working with String output and how to put it into a PSCustomObject. During my exercise I ran into a problem which I can’t fully comprehend at this point.

So I have an array named $results which gets filled with PSCustomObjects like this:

            $results += [pscustomobject]@{
                Adapter = $tempAdapter
                IPv4 = $tempIPv4
                Subnet = $tempSubnet
                Gateway = $tempGateway
            }

This works great and I get the results I expected. (4 NoteProperties containing my desired data)
However if I try to add the PSCustomObjects to the array like this:

            [pscustomobject]$adapterInformation = @{
                Adapter = $tempAdapter
                IPv4 = $tempIPv4
                Subnet = $tempSubnet
                Gateway = $tempGateway
            }

            $results += $adapterInformation

the results are different when I pipe $results into Get-Member. With the second method I don’t get any NoteProperties, while the first method works as intended.
But where is the actual difference if I use a variable to add the PSCustomObject to the array?

Thomas,
Welcome to the forum. :wave:t3:

Using the append operator (+=) is usually a bad idea anyway. Assuming you have a loop you can simply catch the ouput of that loop in a variable creating an array implicitly.

It looks something like this:

$results =
foreach ($item in $collection) {
    $tempAdapter = ''
    $tempIPv4 = ''
    ....
    [pscustomobject]@{
        Adapter = $tempAdapter
        IPv4    = $tempIPv4
        Subnet  = $tempSubnet
        Gateway = $tempGateway
    }
}

Did you read this already?

I’ll have a look how to get rid of the append operator (and I’ll research why it’s bad to use)

I had a look at the link you posted and realized I put the [PSCustomObject] in front of the variable when it should be right in front of the “@”. Since this doesn’t seem to be a syntax error…what did I actually do?

[PSCustomObject]$wrong = @{}
vs.
$right = [PSCustomObject]@{}

Since arrays in PowerShell are immutable you destroy the original array and create a new one with the same name and the added item every time you use the += operator. It is a quite expensive operation and does not perform that well in comparison to the other approach. :man_shrugging:t3:

If I’m not wrong this way you assign a hashtable to the variable $wrong

For arrays, I use this type:

$outobjs = [System.Collections.Generic.List[object]]::new()
$rec = [pscustomobject]@{
     $var1 = 'xyz'
    $var2 = 'abc'
}
$outobjs.add($rec)
1 Like