Paradigm Shift: The Power of Functions that Take Pipelined Input Print E-mail
Written by Darwin Sanoy   
Tuesday, December 16, 2014 1:00am

I wanted to build a simple function that merges all the registry files in a folder as a simple way to configure systems.  It quickly got complex when I realized it would be nice if it could also merge a single file or a bunch of reg files from a entire folder structure.  Then it hit me!


This is exactly the place where receiving pipelined input would give me all those flexible options - without any extra logic code to process the arguments.

First here is the function designed for a single file:

Function Merge-RegFile {

Param ([Parameter(Mandatory=$True)][string]$File) 
Start-Process "regedit.exe" -ArgumentList "/s `"$File`"" -wait


Now we can only use it on a single file like this:

Merge-RegFile "c:\test\settings.reg"

Now we'll make two adaptations to make it capable to receive pipelined input.  The first is to add "ValueFromPipeline=$True" to the parameter and the second is to fit the one line of code in a "Process" block:

Function Merge-RegFile {

Param ([Parameter(Mandatory=$True,ValueFromPipeline)][string]$File)
Process {

Start-Process "regedit.exe" -ArgumentList "/s `"$File`"" -wait



Now this opens up all the following possibilities with no extra parameter handling:

# All .REGs in a Folder
gci c:\temp\*.reg | Select -Expand FullName | Merge-RegFile

# All .REGs in a folder tree
gci c:\temp\*.reg -Recurse | Select -Expand FullName | Merge-RegFile 

# A list of .REGs
"c:\temp\settings.reg", "\\server\share\setup.reg" | Merge-RegFile

So now all the power of Get-ChildItem (or any command that can output a list of file names as strings) is available to create a list of .REGs for the new function.