这个问题在这里已经有了答案:
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/