带有 PSScriptAnalyzer 的 PowerShell 中的 OutputType 属性警告

OutputType attribute warning in PowerShell with PSScriptAnalyzer

Bellow 是声明 OutputType.

的示例函数

我知道这只是为了文档目的,但这里的问题是当我调用 PSScriptAnalyzer 时:

invoke-scriptanalyzer . -IncludeRule PSUseOutputTypeCorrectly

它会告诉我这个:

The cmdlet 'Test-Function' returns an object of type 'System.Object[]' but this type is not declared in the OutputType attribute.

function Test-Function
{
    [CmdletBinding()]
    [OutputType([System.Management.Automation.PSCustomObject[]])]
    param ()

    [PSCustomObject[]] $TestObject = @()

    for ($i = 0; $i -lt 5; $i++)
    {
        $TestObject += [PSCustomObject]@{
            Key1 = "Value1"
            Key2 = "Value2"
        }
    }

    return $TestObject
}

问题是我怀疑这条信息性消息是误报但无法确认。

我想我声明了 OutputType 属性就好了,也许不是?

为什么我需要指定 [OutputType([System.Object[]])] 作为输出类型?如果我回来 PSCustomObject[]?

除非另有说明,否则管道会枚举函数中的任何内容 return,因此当您将任何内容分配给变量时,例如,您的 [psobject[]] 将是 "unpacked" 并填充回动态大小 [object[]].

如果您想 return 按原样使用 Write-Output -NoEnumerate 可枚举集合:

function Test-Function
{
    [CmdletBinding()]
    [OutputType([System.Management.Automation.PSCustomObject[]])]
    param ()

    [PSCustomObject[]] $TestObject = @()

    for ($i = 0; $i -lt 5; $i++)
    {
        $TestObject += [PSCustomObject]@{
            Key1 = "Value1"
            Key2 = "Value2"
        }
    }

    Write-Output $TestObject -NoEnumerate
}