Skip to content

Demonstrates how to add pipeline support to a PowerShell function

License

Notifications You must be signed in to change notification settings

ryan-leap/PipingHotDemo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 

Repository files navigation

A Piping Hot Demo - Add pipeline support to a PowerShell Function!

The Pipeline

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:

PowerShell Pipeline Demo

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!

Pipe objects to my function? Nope.

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:

Function does NOT support 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!

So what's the trick (to get pipeline support)?

Okay, so what's it take to get that pipeline piping? Not much - check out this super simple function which has pipeline support:

Simple Pipeable Function

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.

Let's do this (add pipeline support)!

Okay, so let's steal from the simple example above the things we need to add pipeline support to our original function:

  1. Add the CmdletBinding attribute to the function
  2. Add the ValueFromPipeline attribute to the parameter
  3. Add a begin block (initialization code goes here)
  4. Add a process block (code that needs to run against each piped object goes here)
  5. Add a end block (cleanup code goes here)

Function DOES support the Pipeline

That did it - piping hot fruit coming right up!

Conclusion

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!

About

Demonstrates how to add pipeline support to a PowerShell function

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published