PowerShell 不会将空数组作为数组返回 [英] PowerShell doesn't return an empty array as an array

查看:26
本文介绍了PowerShell 不会将空数组作为数组返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于这有效:

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

为什么这不起作用?

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

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

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

That is, why isn't an empty array returned from the test function?

推荐答案

您的函数不起作用,因为 PowerShell 返回所有 非捕获流输出,而不仅仅是return语句的参数.在此过程中,一个空数组被重整为 $null.但是,您可以通过 前置它来保留返回的数组使用数组构造运算符 (,):

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
}

这篇关于PowerShell 不会将空数组作为数组返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆