Rince2
Rince2

Reputation: 55

How to combine parts of pipe to a function?

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?

Upvotes: 0

Views: 123

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174445

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

Upvotes: 2

Related Questions