George Mauer
George Mauer

Reputation: 122182

How to concat item to pipeline?

I have a regex scanning files and pulling some values out of them in a pipeline:

ls . -Include *.cs -Recurse | Select-String "LoadJsModule" |
   % { $_ -match 'LoadJsModule\("(\S+?)"'; } | ? { $_ } |
   % { $matches[1] } | % { do-Something $_ }

which gets something like

admin
invoices/app
warehouses/app

Let's say I notice that my regex pipeline is getting 90% of the things I want it to grab but missing a few special cases - a string "foo" and a string "bar". How can I add these properly to the pipeline so it contains

admin
invoices/app
warehouses/app
foo
bar

before I pass each to do-Something?

Note that I know I can run the above and then do-Something foo and do-Something bar. There's a dozen different ways to solve the concrete problem. I'm looking specifically to increase my understanding of the PowerShell pipeline so I'd like to know how to mix these values into it directly.

Upvotes: 1

Views: 1424

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200443

You can inject the two strings via the -End parameter of ForEach-Object:

-End<ScriptBlock>
Specifies a script block that runs after processing all input objects.

ls . -Include *.cs -Recurse | Select-String "LoadJsModule" |
  % { $_ -match 'LoadJsModule\("(\S+?)"'; } | ? { $_ } |
  % -Process { $matches[1] } -End { 'foo', 'bar' } | % { do-Something $_ }

Note that using Select-String and -match is redundant. Since you're using the $matches collection later on I'd drop the Select-String. Also, I'd run -match in a Where-Object statement, not a ForEach-Object.

Get-ChildItem -Include *.cs -Recurse |
  Where-Object { $_ -match 'LoadJsModule\("(\S+?)"' } |
  ForEach-Object -Process { $matches[1] } -End { 'foo', 'bar' } |
  ForEach-Object { do-Something $_ }

Upvotes: 1

Related Questions