PowerShell doesn't return an empty array as an

2020-02-01 06:25发布

问题:

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?

回答1:

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
}