Search code examples
arrayspowershell

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?


Solution

  • 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
    }