PowerShell不会将空数组作为数组返回

时间:2013-08-27 22:39:55

标签: arrays powershell

鉴于这是有效的:

$ar = @()
$ar -is [Array]
  True

为什么这不起作用?

function test {
    $arr = @()
    return $arr
}

$ar = test
$ar -is [Array]
  False

也就是说,为什么不是从测试函数返回一个空数组?

2 个答案:

答案 0 :(得分:24)

您的函数不起作用,因为PowerShell返回所有non-captured stream output,而不仅仅是return语句的参数。在此过程中,空数组被限制为$null。但是,您可以在prepending it with the array construction operator,)返回时保留数组:

function test {
  $arr = @()
  return ,$arr
}

答案 1 :(得分:0)

write-output $arr和写$arr一样。 因此该函数仍将返回$null

但是write-output具有选项-NoEnumerate。 这意味着将不枚举空数组 (因此被忽略-因为它是空的)。结果是一个空数组。

上面的答案很短,...

 function test {
     $arr = @()
     write-output $arr -NoEnumerate 
 }
 (test) -is [array]  ## $True