Reputation: 16329
I am trying to add objects to a container in Powershell:
function Person {
param ($FirstName, $LastName)
$object = [PSCustomObject]@{
a=$FirstName;
b=$LastName
}
return $object
}
$container = New-Object -TypeName System.Collections.ArrayList
$result = Person "Billy" "Kid"
[void]$container.Add($result)
[void]$container.Add(Person "Bob" "Hope")
[void]$container.Add({Person "Mad" "Max"})
foreach ($ob in $container) {
Write-Output $ob."a"
}
$container
This line:
[void]$container.Add($result)
works, meaning that the correct value gets printed in the foreach loop. But the lines:
[void]$container.Add(Person "Bob" "Hope")
[void]$container.Add({Person "Mad" "Max"})
does not. Is it not possible to add an element to the container using a function call?
Upvotes: 2
Views: 595
Reputation: 17797
You need to evaluate the expression Person "Bob" "Hope"
before you can add it.
You can do this easily like this:
$container.Add($(Person "Bob" "Hope"))
(Note the added $()
).
Upvotes: 2