PortMan PortMan - 3 months ago 15
PowerShell Question

How to pipe multiple results into a single command

I've got the following pipeline:

dir -recurse *.* | sls -pattern "matching_pattern" | select -unique path


Which gives me an output like this:

Path
----
D:\code\a.txt
D:\code\b.txt


I want it to call the command
gvim a.txt b.txt
.

How do I do this?

Answer

Use Where-Object instead of Select-String for filtering the files, expand the FullName (or Name) property, so you get an array of paths or filenames, and splat it when calling gvim:

$files = Get-ChildItem -Recurse *.* |
         Where-Object { (Get-Content $_.FullName) -match "matching_pattern" } |
         Select-Object -Unique -Expand FullName

& gvim @files

Replace FullName with Name in the Select-Object statement to get just the filenames without path.


If you want to stick with Select-String the approach would be similar:

$files = Get-ChildItem -Recurse *.* |
         Select-String -Pattern "matching_pattern" |
         Select-Object -Unique -Expand Path

& gvim @files

Replace Path with Filename in the Select-Object statement to get just the filenames without path.

Comments