【问题标题】:Prevent ArrayList.Add() from returning the index防止 ArrayList.Add() 返回索引
【发布时间】:2010-01-27 17:57:10
【问题描述】:

有没有办法抑制 ArrayList 的返回值(=Index) 在 Powershell 中(使用 System.Collections.ArrayList)还是应该使用 另一个班级?

$myArrayList = New-Object System.Collections.ArrayList($null)
$myArrayList.Add("test")
Output: 0

【问题讨论】:

  • 虽然这里提供的所有选项都有效,但我个人选择 [void] 的原因很简单:需要速度 :) Measure-Object 是您的朋友。 (有一篇关于这些东西的速度的不错的博客文章,但我暂时找不到,抱歉)

标签: .net powershell arraylist


【解决方案1】:

您可以强制转换为 void 以忽略 Add 方法的返回值:

[void]$myArrayList.Add("test") 

另一种选择是重定向到 $null:

$myArrayList.Add("test") > $null

【讨论】:

  • 我发现其中任何一个的问题是当它是现有序列的一部分时无法输出(例如Write-Output)。例如。我有一个数组列表$ADUsersList,我通过.Add() 添加了一条记录。然后当我尝试将 Write-Output $ADUsersList 作为脚本的一部分时,它在我的 IDE 中是空白的。但是一旦脚本运行完毕,我只需检查$ADUsersList 的内容,它们就会按我的预期打印出来。
  • 我认为您还有其他问题。在 PS >= 5 中试试这个,你会看到它输出了列表的内容:$l = [System.Collections.ArrayList]::new(); $l.Add("test") > $null; $l
  • 你是对的;确实有效。不知道我的情况是什么导致了差异(我通过[void]$ArrayList.Add($objRecord)将有序的PSObject记录插入到ArrayList中。如果我在脚本运行后检查$ArrayList,但在脚本期间任何Write-Output尝试显示$ArrayList 的内容失败)。无论如何,很高兴看到我弄错了。这意味着使用 ArrayLists 进行调试比我想象的要容易一些。
【解决方案2】:

另外两个选项:)

管道到out-null

$myArrayList.Add("test") | Out-Null  

将结果赋值给$null:

$null = $myArrayList.Add("test")

【讨论】:

  • 您能否谈谈将管道传递到 Out-Null 与 > $null 或分配给 $null 与强制转换为 [void] 的效率?这四种中哪一种最有效?
  • 为什么arraylist会在列表中添加空值
猜你喜欢
  • 2013-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 2014-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多