PowerShell OutputType 属性不起作用

PowerShell OutputType attribute not working

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 函数返回吗?

谢谢

显然,您的期望是正确的。我必须说我很惊讶它对 [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,我无法获得定义相同 OutputType 的任何现有 cmdlet 来为字符串的方法提供制表符补全:

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's UserVoice.

上进行报道