Author Posts

July 31, 2018 at 2:56 pm

Hi all,

I am probably being completely stupid but this is driving me crazy,

I have two variables one from a loop of a text file '$Server' and the other the results from a scriptblock '$CurrentSystem'
I want to add these two variables into a new variable called '$FinalList

So I write '$FinalList += $Server += $CurrentSystem
However I receive the dreaded 'Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named 'op_Addition'. message.

I have already called the vriables as array variables $FinalList = @() etc.

I have read a few articles on how to add these two objects together into a new variable but none of them seem to be doing what I require here.

What do you think?

Thanks.

August 1, 2018 at 4:48 am

You are not providing enough for this to be clear.

Based on what is where, you are using the assignment operators is an odd way. You are incrementing (a math operation vs concatenation or building and array, hashtable, etc...)

What are the values of these?
$Server += $CurrentSystem

If you are creating a collection, then no, this will never work, like this.
If these are just a string, then it should be this...

$FinalList = ($Server + ' ' + $CurrentSystem)

... but then you are overwriting the value, since this is a loop and last in wins.

You need to take a look at PSCustomObject, calculated properties, and hashtbles. See the built-in / online help for that and or the below and others like them.

'mikecrowley.us/2012/04/17/combining-powershell-cmdlet-results'
'powershell.org/forums/topic/how-to-combine-data-from-multiple-cmdlets'

If you are saying that you are using a list of servers, the using a block to get WMI date about that computer, then there should be little reason to try and combine this into another variable to get a report, since the name is already in the WMI info of the computer data pulled.

Just pull the computer info directly and list out the needed property information.

August 1, 2018 at 2:28 pm

Here is a couple methods that you can try. Notice that these methods only capture properties are the same in both objects:

$object1 = New-Object -TypeName PSObject -Property @{Name="Bill";Age=22} #| Select Name, Age, Hobby
$object2 = New-Object -TypeName PSObject -Property @{Name="Sam";Age=21;Hobby="Kittens"}

$final = @()
$final += $object1
$final += $object2

$final

$final2 = @()
$final2 = $object1, $object2
$final2

Output (for both methods):

Age Name
--- ----
 22 Bill
 21 Sam 

If you have an extra property, you can kind of cheat by using Select to generate a new object with the NULL value

$object1 = New-Object -TypeName PSObject -Property @{Name="Bill";Age=22} | Select Name, Age, Hobby

then you get:

Name Age Hobby  
---- --- -----  
Bill  22        
Sam   21 Kittens