Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell doesn't return an empty array as an array

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?

like image 718
user2197005 Avatar asked Aug 27 '13 22:08

user2197005


People also ask

Can you return an empty array?

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 .

Should return an empty array if the property does not exist?

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.

What happens when an array is empty?

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.


1 Answers

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 } 
like image 178
Ansgar Wiechers Avatar answered Sep 26 '22 12:09

Ansgar Wiechers