组合多个 powershell cmdlet 输出

combine multiple powershell cmdlet outputs

我需要合并多个 Power Shell 脚本的输出,以便在 .NET 中使用 CmdLets 作为管道输出。

例如:

Command-GetA  -combine  Command-GetB | Command-GetD

所以我想通过管道将 GetAGetB 的输出发送到 GetD。是否有使用 powershell 脚本或 .NET cmdlet 执行此操作的紧凑方法?除了将输出存储在数组中然后将其传递给管道之类的方法之外?

另一个复杂的例子可能是:

Command-GetA  -combine  ( Command-GetB | Command-GetD ) | Command-GetF

这应该结合 GetAGetB|GetD 作为管道输入发送到 GetF

编辑:

如果我能做这样的事情就好了 - @( GetA ; GetB) -ConvertToASingleList | GetC

因此 OutputOfGetAOutputOfGetB 不应在 GetC 上单独调用。两者都应作为组合数组或列表对象传递给 GetC

嗯,不是很紧凑,但我会这样做:

    $alldata = @()

    $geta = command-geta
    $getb = command-getb
    $getc = command-getc


    #of course creating a function would be much more nicer in case the structure of A, B and C is the same

    foreach ($a in $geta)
        {
        $temp = New-Object System.Object
        $temp | Add-Member -MemberType NoteProperty -Name "aonedata" -Value $a.one
        $temp | Add-Member -MemberType NoteProperty -Name "atwodata" -Value $a.two
        $alldata += $temp   
        }

    foreach ($b in $getb)
        {
        $temp = New-Object System.Object
        $temp | Add-Member -MemberType NoteProperty -Name "bonedata" -Value $b.one
        $temp | Add-Member -MemberType NoteProperty -Name "btwodata"    -Value $b.two
        $alldata += $temp   
        }

    foreach ($c in $getc)
        {
        $temp = New-Object System.Object
        $temp | Add-Member -MemberType NoteProperty -Name "conedata" -Value $c.one
        $temp | Add-Member -MemberType NoteProperty -Name "ctwodata" -Value $c.two
        $alldata += $temp   
        }

    write-host $alldata
    $alldata | convertto-csv | out-file "c:\temp\lotsofdata.txt"

@PetSerAl 推荐的解决方案似乎符合您的要求:

PS C:\> function Foo { 1..3 }
PS C:\> function Bar { 2..4 }
PS C:\> & { Foo; Bar | % { $_ + 2 } } | oh
1
2
3
4
5
6

脚本块将所有输出组合成一个数组。此行为记录在 about_Script_Blocks:

A script block returns the output of all the commands in the script block, either as a single object or as an array.

这给了我想要的最终结果:

$(命令-GetA;命令-GetB)|小组结果 |命令-GetC

因此,如果 "GetC" 是一个串联的 cmdlet,整个 "GetC" cmdlet 代码 运行 仅对我的所有输入文件执行一次(每次我 运行 "concat")

虽然上面的答案都是正确的,但我的要求有点不同:)

编辑:

这太完美了!

,@(命令-GetA;命令-GetB)|命令-GetC

感谢@PetSerAl

如果有人遇到上述方法不起作用的奇怪边缘情况,您也可以使用 -join。

EG.

-join($(Command-GetA), "," , $(Command-GetB))

这将生成适合 csv 的字符串。