如何在管道命令后将结果添加到数组或集合?

How to add a result to array or Collection after a pipeline command?

如何将管道的输出添加到现有数组中?

我做了类似那个例子的事情:

$FirstCollection = New-Object System.Collections.ArrayList
foreach ($item in $OtherCollection) {
    if ($item -ne "blabla") {
        $result | 
        Where-Object { ($_.ID -Match 1) } |
        Group-Object -Property id, LevelDisplayName, LogName -NoElement | 
        Sort-Object -Property count -Descending |
        **This output must going into the $FirstCollection**
    }

    if ($item -ne "bliblablubb") {
        $result | 
        Where-Object { ($_.ID -Match 1) } |
        Group-Object -Property id, LevelDisplayName, LogName -NoElement | 
        Sort-Object -Property count -Descending |
        **This output must going into the $FirstCollection as well**
    }
}

我应该如何将最后一个输出添加到数组中?数组也可以是简单的 $array = @().

我需要这个,因为在 foreach 之后我必须将数组条目输出到文件中。 在最后一个管道之后,我得到一个计数、一个值和一个字符串,我需要逐行显示所有结果。

如果我使用 Out-File... 在管道之后直接输出,我会得到这样的结果:

Count Name                                                               
----- ----                                                               
   69 123, someText, someMoreText
Count Name                                                               
----- ----                                                               
   50 456, someText, someMoreText
Count Name                                                               
----- ----                                                               
   25 789, someText, someMoreText

但我需要:

Count Name                                                               
----- ----    
 69 123, someText, someMoreText 
 50 456, someText, someMoreText
 25 789, someText, someMoreText

要在 PowerShell 中添加到 ArrayList,您不需要管道。而是使用 ArrayList.Add() 函数或简单地使用 +=(就像在 C# 中一样)。

$FirstCollection = New-Object System.Collections.ArrayList
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
    }
}

我相信这也适用于 $FirstCollection = @()