保留一些管道的值以用于最终输出

Retain values from some pipes for final output

你是怎么做到像

这样的事情的
PS> A | B | C | Format-Table PropertyFromA, PropertyFromB, PropertyFromC

例如

gci -r -i *.txt | Get-Content | where {$_.Contains("SomeText")} | FormatTable -Property {$_.Directory, $.Name}

在这种情况下,gci 输出将具有 Directory、Name 属性,但当我通过 Get-Content 进行管道传输时,这些属性将丢失。我如何存储它并在稍后通过管道传输到 Format-Table 时使用。所有这些都可以在一个管道链命令中很好地实现吗?

对您的命令稍作修改即可:

gci -r -i *.txt | ? { (gc $_.FullName) -Match "SomeText" } | FormatTable Directory,Name

Arco444 对这种情况有正确的答案。如果您没有向我们展示您问这个问题的真正原因,或者如果其他人来到这里,我将展示两个示例来解决这个问题。

Get-ChildItem -Recurse -filter *.txt | ForEach-Object{
   $_ | Add-Member -MemberType NoteProperty -Name FileData -Value (Get-Content $_.FullName) -PassThru
} | Where-Object{($_.Filedata).Contains("SomeText")} | 
Format-Table name,directory


Get-ChildItem -Recurse -filter *.txt | 
    Select Name,Directory,@{Label="FileData";Expression={Get-Content $_.FullName}} | 
    Where-Object{($_.Filedata).Contains("SomeText")} | 
    Format-Table name,directory

这些"oneliners"都是在Get-ChildItem创建的对象上加上属性的例子。新的 属性 FileData 就是您过滤的对象。这个逻辑也可以用在其他方面。