Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Get-Process | Grep foo

Is that possible?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading