Reputation: 929
I am trying to get my head around what is going on here, and I was wondering if anyone knew of a resource that might point me in the right direction, or could explain it a bit for me.
I am trying to create a PSCustomObject variable, and then members to it, like this:
$myObject += [PSCustomObject]@{
FirstName = 'Bill'
LastName = 'Bobbins'
Age = '30'
}
$myObject += [PSCustomObject]@{
FirstName = 'Ben'
LastName = 'Bobbins'
Age = '40'
}
So the first bit of code executes fine, but the second bit results in an error "Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named 'op_Addition'." Also, if I pipe $myObject to get-member, I can see that $myObject is TypeName: System.Management.Automation.PSCustomObject.
Now, if I set $myObject to be an empty array first, and then try to add members, I am successful. This code works without error:
$myObject=@()
$myObject += [PSCustomObject]@{
FirstName = 'Bill'
LastName = 'Bobbins'
Age = '30'
}
$myObject += [PSCustomObject]@{
FirstName = 'Ben'
LastName = 'Bobbins'
Age = '40'
}
If I now pipe $myObject to get-member, I still get TypeName: System.Management.Automation.PSCustomObject. So my question is, why am I allowed to add multiple members to $myObject in the second example, but not in the first, when the data type is the same for both examples?
Any help is muchly appreciated!
Thanks
Upvotes: 2
Views: 1260
Reputation: 10019
The issue here is with how Get-Member
/the pipeline works - it's tripped me up before!
This will unroll the array, and give you the type of each element as it passes it across the pipeline:
$myObject | Get-Member
This will pass the whole object, and correctly give you the type as System.Object[]
Get-Member -InputObject $myObject
You can test this out by for example adding $myObject += "test string"
to the end of your code and trying to get members both ways. The first will return both PSObject
and String
types.
Sidepoint: The $myObject = @()
line can be avoided by specifying you are creating an array the first time you declare $myObject
. Example:
[array]$myObject = [PSCustomObject]@{
[PSCustomObject[]]$myObject = [PSCustomObject]@{
Upvotes: 3