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:
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:
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?
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.
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.
If I’m not wrong this way you assign a hashtable to the variable $wrong