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?
To return an empty array from a function, we can create a new array with a zero size. In the example below, we create a function returnEmptyArray() that returns an array of int . We return new int[0] that is an empty array of int . In the output, we can get the length of the array getEmptyArray .
If the array contains no even elements, it should return an empty array. If the property at the given key is not an array, it should return an empty array. If there is no property at the given key, it should return an empty array.
If the length of the object is 0, then the array is considered to be empty and the function will return TRUE. Else the array is not empty and the function will return False.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With