Home > Software design >  How to combine parts of pipe to a function?
How to combine parts of pipe to a function?

Time:02-16

To have a "grep"-like experience in Powershell, I use this (e.g. to find a process with "foo" in its name):

Get-Process | Out-String -Stream | Select-String -SimpleMatch -Pattern "foo"

I would like to write a function Grep(), that takes input from the pipe, that does the same. Basically I am looking for a way to combine the last two pipe elements. So that I could simply write:

Get-Process | Grep foo

Is that possible?

CodePudding user response:

Use the $input automatic variable to automatically enumerate any pipeline input provided, then grab the value of the first command line argument from $args:

function grep {
    $input |Out-String -Stream |Select-String -SimpleMatch -Pattern $args[0]
}

Now you can do:

Get-Process |grep foo
  • Related