如何将PowerShell管道命令的输出添加到已有数组或集合中
解决方案
方法1:使用普通PowerShell数组
如果你用基础的$array = @()类型数组,直接把管道的输出整体追加到数组即可,代码修改如下:
# 初始化空数组 $FirstCollection = @() foreach ($item in $OtherCollection) { if ($item -ne "blabla") { $FirstCollection += $result | Where-Object { ($_.ID -Match 1) } | Group-Object -Property id, LevelDisplayName, LogName -NoElement | Sort-Object -Property count -Descending } if ($item -ne "bliblablubb") { $FirstCollection += $result | Where-Object { ($_.ID -Match 1) } | Group-Object -Property id, LevelDisplayName, LogName -NoElement | Sort-Object -Property count -Descending } }
这种方法语法最简单,适合数据量不大的场景,PowerShell会自动处理数组扩容逻辑。
方法2:使用ArrayList(性能更优)
如果处理的数据量较大,推荐用System.Collections.ArrayList,它的追加效率远高于普通数组,用法如下:
$FirstCollection = New-Object System.Collections.ArrayList foreach ($item in $OtherCollection) { if ($item -ne "blabla") { $output = $result | Where-Object { ($_.ID -Match 1) } | Group-Object -Property id, LevelDisplayName, LogName -NoElement | Sort-Object -Property count -Descending # $null用来屏蔽方法返回的索引值,避免多余内容混入集合 $null = $FirstCollection.AddRange($output) } if ($item -ne "bliblablubb") { $output = $result | Where-Object { ($_.ID -Match 1) } | Group-Object -Property id, LevelDisplayName, LogName -NoElement | Sort-Object -Property count -Descending $null = $FirstCollection.AddRange($output) } }
输出到文件的正确方式
你之前每次管道后直接调用Out-File会重复表头,是因为每次调用Out-File都会为当前输入的对象集自动生成表头。你只需要等所有内容都收集到数组后,统一调用一次输出即可,就能得到你要的格式:
$FirstCollection | Out-File -FilePath "你的输出路径.txt" -Encoding UTF8
内容的提问来源于stack exchange,提问作者Larry
相关产品推荐
相关产品推荐

