PowerShell函数永远不会返回空数组

时间:2019-03-27 09:13:19

标签: arrays powershell

我希望函数始终返回一个数组,即使它为空@()。我注意到,如果函数返回@(MyFunction),仅用$null强制一个函数的输出将返回一个包含1个元素($null)的数组。我想要的是强制将结果强制为空数组@()

那么我们如何从PowerShell中的函数返回空数组?

function ReturnAnEmptyArray() {return @()}
function ReturnNull() {return $null}

$a = @()
Write-Host "`$a is an empty array of length $($a.length) and type $($a.gettype())"
$b = ReturnAnEmptyArray
Write-Host "`$b is null: $($b -eq $null) but should be an empty array @()"
$c = @(ReturnNull)
Write-Host "`$c is an array of length $($c.length) and type $($c.gettype()) and `$c[0] is null $($c[0] -eq $null)"
$d = [array](ReturnNull)
Write-Host "`$d is just plain `$null $($d -eq $null) and not an array"

输出:

$a is an empty array of length 0 and type System.Object[]
$b is null: True but should be an empty array @()
$c is an array of length 1 and type System.Object[] and $c[0] is null True
$d is just plain $null True and not an array

有没有确定的方法让函数返回空数组?

function ConvertTo-Array($Obj) {
    # Return array as array
    if ($Obj -is [array]) {return $Obj}
    # Return $null as empty array @() => Fails to deliver @()
    elseif ($Obj -eq $null) {return @()}
    # Other values/objects (e.g. strings) are wrapped in an array
    else {return @($Obj)}
}

1 个答案:

答案 0 :(得分:0)

从Ansgar引用相同的答案应该可以帮助您返回,但这不是一个很好的应对方式

function returnemptyarray {
  $arr = @()
  return ,$arr
}

$a = returnemptyarray 
$a.gettype()