2

OutputType属性应该通过智能感知提供类型信息。但是它没有按预期工作。

我已经在 PSReadline 和 PowerShell ISE 中对此进行了测试,它们的工作方式相同。

以下是我正在使用的示例函数:

Function Get-FirstChar
{
    [OutputType([String])]
    [CmdletBinding()]

    param(
      [Parameter(Mandatory=$true, ValueFromPipeline=$true)][string[]]$Strings
    )

    process {
        foreach ($str in $Strings) {
            $str.SubString(0, 1);
        }   
    }
}

当我做:


"John","Simon" | Get-FirstChar | % { $_.<TAB> }

我得到建议(无论平台如何):

Equals       GetHashCode  GetType      ToString

但是,当我这样做时:

("John","Simon" | Get-FirstChar).<TAB>

然后我得到所有的字符串方法等SubString

我也尝试了一个字符串数组String[]作为输出类型,但它仍然不起作用:(

有人可以了解如何使用OutputType属性来表示将从 powershell 函数返回一个或多个字符串吗?

谢谢

4

1 回答 1

2

显然,您的期望是正确的。我必须说我很惊讶它不起作用,[string]因为它适用于其他复杂类型:

function Get-ProcessEx {
    [OutputType([System.Diagnostics.Process])]
    param ()
}

Get-ProcessEx | ForEach-Object { $_.}

当我尝试使用时,[string]我只得到属性(这对字符串不是很有帮助,它们唯一的属性是Length)。我认为这是一个错误,或者是 PowerShell ISE 和 PSReadline 等工具响应从函数返回的对象是字符串的信息的方式的限制。例如,如果您尝试对其他简单类型进行相同操作,结果符合预期:

function Get-Int {
    [OutputType([int])]
    param ()
}

Get-Int | ForEach-Object { $_. }

它似乎也影响了 cmdlet,我无法获得任何现有的定义相同的 cmdletOutputType来为字符串方法提供制表符补全:

Get-Command | Where-Object { $_.OutputType.Type -eq [String] }
# Join-Path, not too surprisingly, returns System.String...
Join-Path -Path C:\temp -ChildPath a.txt | ForEach-Object { $_.}

我想无论哪种情况,都值得报告PowerShell 的 UserVoice。

于 2016-12-27T19:49:41.270 回答