Retain values from some pipes for final output

2019-08-05 05:19发布

问题:

How do you do something like

PS> A | B | C | Format-Table PropertyFromA, PropertyFromB, PropertyFromC

So for example

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

In this case gci output will have properties of Directory, Name but these will be lost when I pipe through Get-Content. How do I store this and make use later when piped to Format-Table. Can all this be achieved nicely in a single pipe chain command?

回答1:

A small modification to your command will work:

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


回答2:

Arco444 has the right answer for this situation. On the off chance you are not showing us the real reason you are asking this question, or if others make their way here, I am going to show two examples that address this question as well.

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

These "oneliners" are both examples that add a property to the objects created by Get-ChildItem. The new property FileData is then what you filter on. This logic can be applied in other ways as well.