【问题标题】:Correctly return array in powershell在 powershell 中正确返回数组
【发布时间】:2020-05-19 17:45:40
【问题描述】:

我是 powershell 新手,尝试了一个生成数组的函数。

function array_create {
    $array = [System.Collections.ArrayList]@()
    $array.Add('hello')
    $array.Add('world')
    return $array
}

$arr = array_create
foreach($a in $arr){
   $a
}

即使我把 @() 放在函数调用周围,输出也是

0
1
hello
world

我如何正确返回一个只有值(没有数字)的数组,为什么会发生这种情况?

【问题讨论】:

标签: powershell


【解决方案1】:

这是因为Add method of ArrayList Class 返回一个[int] 值:

$array = [System.Collections.ArrayList]@()
$array.Add
OverloadDefinitions
-------------------
int Add(System.Object value)
int IList.Add(System.Object value)

使用[void]$array.Add('hello')$null = $array.Add('hello')

$array.Add('hello') | Out-Null 是可能的,但不建议在循环中使用,因为它会对性能产生负面影响。

【讨论】:

  • 感谢 JosefZ 的提示和解释
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-07
  • 1970-01-01
  • 2019-05-05
  • 2017-11-24
  • 2017-04-17
相关资源
最近更新 更多