Preserving PowerShell function return type

前提是你 提交于 2020-01-02 01:46:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!