Is this question about "[System.Collections.Generic.List[string]]
as return value" I got an interesting answer from @Ash about using $PSCmdlet.WriteObject()
instead of Return
to avoid pipeline pollution. And it seemed to work in that context. However, in trying to explain this to someone, I made this little example, using an ArrayList
instead, since I know that pollutes the pipeline every time. And here it does NOT work. Without the ArrayList lines, both return a type of [System.String]
. With those lines they BOTH return [System.Object]
. And if I prefix the ArrayList
line with [Void]
to redirect the pollution, it's back to [System.String]
.
I have verified that in both failure cases the .Count
of the returned object is 2. Which got me thinking, is this only a solution for the unroll problem? So I revised the test to use a System.Collections.Generic.List[string]
for the return, and I find that without the ArrayList
to pollute, WriteObject works, while return
only works with the unroll fix, i.e. return ,$return
. Add the pollution back in, and they both get polluted.
So, was my understanding wrong, and this solution is only applicable to the unroll problem? And if so, is there anything specific to recommend one approach over the other?
And, IS THERE a real solution to the pipeline pollution problem with functions? Or is this just how functions work, and the answer is to use classes where you have complete control over return types, and PowerShell doesn't pour it's effluent into your variables willy nilly?
function ReturnObject () {
[String]$return = 'Return a string'
(New-Object System.Collections.ArrayList).Add('Pollution')
return $return
}
function WriteObject {
[CmdletBinding()]
param ()
[String]$writeObject = 'Writeobject a string'
(New-Object System.Collections.ArrayList).Add('Pollution')
$PSCmdlet.WriteObject($writeObject)
}
CLS
$Returned = ReturnObject
Write-Host "$Returned ($($Returned.GetType().FullName))"
$Written = WriteObject
Write-Host "$Written ($($Written.GetType().FullName))"
And the Generic.List variant
function ReturnObject () {
$return = New-Object System.Collections.Generic.List[string]
$return.Add('Return a List')
(New-Object System.Collections.ArrayList).Add('Pollution')
return ,$return
}
function WriteObject {
[CmdletBinding()]
param ()
$writeObject = New-Object System.Collections.Generic.List[string]
$writeObject.Add('Writeobject a List')
(New-Object System.Collections.ArrayList).Add('Pollution')
$PSCmdlet.WriteObject($writeObject)
}
CLS
$Returned = ReturnObject
Write-Host "($($Returned.GetType().FullName)) $($Returned.Count)"
$Written = WriteObject
Write-Host "($($Written.GetType().FullName)) $($Returned.Count)"