How do I force a function to return a single element array instead of the contained object?

左心房为你撑大大i 提交于 2021-01-28 07:52:54

问题


I have a function (actually several instances of this), but there are times that it may return a list of several elements, and there are times that it may return a single element. I want the function to return an array ([System.Object[]]) every time so that (on the receiving end), I can always anticipate it being an array and index into it, even if I am just pulling the 0th element.

I've tried casting the return type multiple ways (see code below) ... including (for example) return @("asdf"), return [System.Object[]]@("asdf") and similar, but it seems that the only to get a consistent behavior is to add a second null element in the array ... which feels wrong to me. (See code below)

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" 

回答1:


If I understand your question, you can use the , operator when returning the value; e.g.:

function fn1 {
  ,@("asdf")
}

The function will output a single-element array.




回答2:


As an alternative to wrapping in an extra array, use Write-Output -NoEnumerate:

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

or, in cmdlet-bound/advanced functions prior to version 4.0:

function fn1 {
  [CmdletBinding()]
  param()

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


来源:https://stackoverflow.com/questions/56791856/how-do-i-force-a-function-to-return-a-single-element-array-instead-of-the-contai

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!