user2197005
user2197005

Reputation: 445

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?

Upvotes: 43

Views: 9979

Answers (3)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

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
}

Upvotes: 59

rkbennett
rkbennett

Reputation: 31

Another thing to keep in mind with the "prepend ','" solution, is that if you intend to serialize the data afterwards, you're going to run into some issues. What , appears to actually do is wrap whatever variable it's prepending into an array. so $null becomes [], "test" becomes ["test"], but...... ["foo","bar"] becomes [["foo","bar"]], which is obviously an issue from a serialization standpoint.

Upvotes: 3

Marty
Marty

Reputation: 336

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

Upvotes: 3

Related Questions