如何强制函数返回单个元素数组而不是所包含的对象?

时间:2019-06-27 13:14:23

标签: powershell powershell-5.0

我有一个函数(实际上是该函数的多个实例),但是有时它可能返回几个元素的列表,并且有时它可能返回单个元素。我希望函数每次都返回一个数组([System.Object[]],以便(在接收端)我总是可以预期它是一个数组并对其进行索引,即使我只是拉第0个元素也是如此。 / p>

我尝试过多种方式转换返回类型(请参见下面的代码)...包括(例如)return @("asdf")return [System.Object[]]@("asdf")和类似方法,但似乎唯一获得一致的方法行为是在数组中添加第二个null元素……这对我来说是错误的。 (请参见下面的代码)

function fn1 {
    return @("asdf")
}

function fn2 {
    return [array]@("asdf")
}

function fn3 {
    return [System.Object[]]@("asdf")
}

function fn4 {
    # This works but with the side effect of sending a null string that is not actually necessary
    return @("asdf",$Null)
}

$v = fn1            # Same for fn2, fn3.
$v.GetType().Name   # Expected: Object[], Actual: String
$v[0]               # Expected: "asdf", Actual: "a"

$v = fn4
$v.GetType().Name   # Expected: Object[], Actual: Object[]
$v[0]               # Expected: "asdf", Actual: "asdf" 

2 个答案:

答案 0 :(得分:3)

如果我理解您的问题,则可以在返回值时使用,运算符;例如:

function fn1 {
  ,@("asdf")
}

该函数将输出一个单元素数组。

答案 1 :(得分:2)

作为包装在额外数组中的替代方法,请使用Write-Output -NoEnumerate

function fn1 {
  Write-Output @('asdf') -NoEnumerate
}

,或者在4.0版之前的cmdlet绑定/高级功能中:

function fn1 {
  [CmdletBinding()]
  param()

  $PSCmdlet.WriteObject(@('asdf'), $false)
}