I want a function to always return an array, even if it's empty @(). I've noticed that just coercing the output of a function with @(MyFunction) will return an array with 1 element ($null) if the function returns $null. What I want is to coerce the result to empty array @() instead.
So how can we return an empty array from a function in 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"
Output:
$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
Is there any sure way to have a function return an empty 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)}
}