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.
Note. It is not necessary to specify a Return command in a PowerShell function. The value of any variable or object that is displayed directly in the body of the function will be available as the function output. The return type of the function is System.
You can also save your function in a PowerShell script file. Type your function in a text file, and then save the file with the . ps1 filename extension.
The return keyword exits a function, script, or script block. It can be used to exit a scope at a specific point, to return a value, or to indicate that the end of the scope has been reached.
$input. Contains an enumerator that enumerates all input that's passed to a function. The $input variable is available only to functions and script blocks (which are unnamed functions). In a function without a begin , process , or end block, the $input variable enumerates the collection of all input to the function.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With