保留PowerShell函数的返回类型 [英] Preserving PowerShell function return type

查看:61
本文介绍了保留PowerShell函数的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PowerShell脚本中,我需要使用以下签名调用.NET方法:

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
}

然后我调用该方法:

$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

因此PowerShell出于某种原因会转换为 CustomList ,其中两个项目分别指向 obje ct [] 有两个项目,无法在方法调用时将其转换回原样。如果我调用 ConvertTo-CustomList(@ {'foo'='1'}),则仅返回 string

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.

那么如何强制 ConvertTo-CustomList 函数返回原始的 CustomList ?我不想就地初始化 CustomList ,因为在实际代码中,初始化比本例中的更为复杂。

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.

一种可能的解决方法是使用 Add-Type Commandlet在C#中实现辅助函数,但我希望将代码保留为单一语言。

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.

推荐答案

return $list

导致集合拆散并逐一吸取。这就是PowerShell的本质。

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

这篇关于保留PowerShell函数的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆