Given that this works:
$ar = @()
$ar -is [Array]
True
Why doesn't this work?
function test {
$arr = @()
return $arr
}
$ar = test
$ar -is [Array]
False
That is, why isn't an empty array returned from the test function?
Given that this works:
$ar = @()
$ar -is [Array]
True
Why doesn't this work?
function test {
$arr = @()
return $arr
}
$ar = test
$ar -is [Array]
False
That is, why isn't an empty array returned from the test function?
Your function doesn't work because PowerShell returns all non-captured stream output, not just the argument of the return
statement. An empty array is mangled into $null
in the process. However, you can preserve an array on return by prepending it with the array construction operator (,
):
function test {
$arr = @()
return ,$arr
}
$arr.add(1)
which was outputting the count of the array after. Doing $x = $arr.add(1)
fixed the issue. Hacky.
– Jim W.
Jul 3 '14 at 15:14
... | Out-Null
or ... >$null
to suppress undesired output. I wouldn't consider returning all non-captured output a bad idea per se, though, it's just unexpected for most people with a background in other programming languages. When used properly it can actually simplify returning data from a function, because you don't have to collect all desired output in a variable before returning it.
– Ansgar Wiechers
Jul 5 '14 at 20:50
return $x
is just shorthand for Write-Output $x; return
. Clearly the keyword should be ExitSub and it shouldn't accept an argument.
– Sam Porch
May 20 '15 at 1:21
write-output $arr
is as afaik the same as just writing $arr
.
So the function will still return $null
.
But write-output
has the option -NoEnumerate
.
That means the empty Array will not be enumerated
(and therefore ignored - because it's empty). The result is an empty array.
admittedly the above answer is much shorter, ...
function test {
$arr = @()
write-output $arr -NoEnumerate
}
(test) -is [array] ## $True