问题
In my PowerShell script I need to call a .NET method with the following signature:
class CustomList : System.Collections.Generic.List<string> { }
interface IProcessor { void Process(CustomList list); }
I made a helper function to generate the list:
function ConvertTo-CustomList($obj)
{
$list = New-Object CustomList
if ($obj.foo) {$list.Add($obj.foo)}
if ($obj.bar) {$list.Add($obj.bar)}
return $list
}
Then I call the method:
$list = ConvertTo-CustomList(@{'foo'='1';'bar'='2'})
$processor.Process($list)
However, the call fails with the following error:
Cannot convert argument "list", with value: "System.Object[]", for "Process" to type "CustomList"
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
So PowerShell by some reason converts a CustomList
with two items to an object[]
with two items and cannot convert it back at method call. If I call ConvertTo-CustomList(@{'foo'='1'})
, just a string
is returned.
I tried to put a cast here and there, but this does not help, the execution fails at the point of cast after function return.
So how can force the ConvertTo-CustomList
function to return the original CustomList
? I would not like to initialize the CustomList
in-place because in real code the initialization is more complex than in this example.
A possible workaround is to implement the helper function in C# using the Add-Type
commandlet, but I would prefer to keep my code in single language.
回答1:
return $list
causes the collection to unravel and get "piped" out one by one. Such is the nature of PowerShell.
You can prevent this, by wrapping the output variable itself in a 1-item array, using the unary array operator ,
:
return ,$list
来源:https://stackoverflow.com/questions/38257354/preserving-powershell-function-return-type