With PowerShell you can 'pipe' objects from one cmdlet to another. Once you get the hang of the filtering and sorting cmdlets you can leverage the pipeline to quickly refine results down to just that which you are after:
This is a great feature of the shell and as it turns out (with just a little bit of code) you can add pipeline support to the functions you write. Interested? Follow along!
Below is a simple function which accepts one or more pieces of fruit as an argument. As you can see though, that same fruit can't be passed in from the pipeline:
Notice that we can't pipe data into our function because our Fruit
parameter doesn't support it. Well that's no good - let's fix it!
Okay, so what's it take to get that pipeline piping? Not much - check out this super simple function which has pipeline support:
Notice the begin
block gets entered once at the beginning, the process
block gets entered for each object in the pipeline, and the end
block get entered once at well, the end.
Okay, so let's steal from the simple example above the things we need to add pipeline support to our original function:
- Add the CmdletBinding attribute to the function
- Add the ValueFromPipeline attribute to the parameter
- Add a begin block (initialization code goes here)
- Add a process block (code that needs to run against each piped object goes here)
- Add a end block (cleanup code goes here)
That did it - piping hot fruit coming right up!
One of the things that makes PowerShell so slick is its support for the pipeline. You can extend that pipeline coolness into your own functions by adding in just a few lines of code - so why not do it? Enjoy!