arrays - PowerShell 函数永远不会返回空数组

标签 arrays powershell

这个问题在这里已经有了答案:





PowerShell doesn't return an empty array as an array

(2 个回答)


3年前关闭。




我希望一个函数总是返回一个数组,即使它是空的 @() .我注意到只是用 @(MyFunction) 强制函数的输出如果函数返回 $null,将返回一个包含 1 个元素 ($null) 的数组.我想要的是将结果强制为空数组 @()反而。

那么我们如何从 PowerShell 中的函数返回一个空数组呢?

function ReturnAnEmptyArray() {return @()}
function ReturnNull() {return $null}

$a = @()
Write-Host "`$a is an empty array of length $($a.length) and type $($a.gettype())"
$b = ReturnAnEmptyArray
Write-Host "`$b is null: $($b -eq $null) but should be an empty array @()"
$c = @(ReturnNull)
Write-Host "`$c is an array of length $($c.length) and type $($c.gettype()) and `$c[0] is null $($c[0] -eq $null)"
$d = [array](ReturnNull)
Write-Host "`$d is just plain `$null $($d -eq $null) and not an array"

输出:
$a is an empty array of length 0 and type System.Object[]
$b is null: True but should be an empty array @()
$c is an array of length 1 and type System.Object[] and $c[0] is null True
$d is just plain $null True and not an array

有没有办法让函数返回一个空数组?

function ConvertTo-Array($Obj) {
    # Return array as array
    if ($Obj -is [array]) {return $Obj}
    # Return $null as empty array @() => Fails to deliver @()
    elseif ($Obj -eq $null) {return @()}
    # Other values/objects (e.g. strings) are wrapped in an array
    else {return @($Obj)}
}

最佳答案

引用 Ansgar 的相同答案应该可以帮助您返回,但这不是处理的好方法

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

$a = returnemptyarray 
$a.gettype()

关于arrays - PowerShell 函数永远不会返回空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55373450/

相关文章:

ruby - 在 Ruby 中将不连续的数据切片为连续的部分

javascript - 使用 IIFE 时抛出 “` TypeError `: ` [0,1] ` is not a function”

PowerShell Where对象与Where方法

.Net Windows 更新查询

internet-explorer - IE COM 的 querySelectorAll 在 IE 8 中不起作用

powershell 获取 aduser 扩展属性12

php - PHP 如何处理将自身作为元素引用的数组?

c++ - 数组初始化问题

arrays - 将 Swift 数组转换为 NSData 以进行 NSUserDefaults.StandardUserDefaults 持久存储

powershell - 在PowerShell中变量旁边时的冒号(:)问题