PowerShell Function Factory

by Doug Finke on September 12, 2009

in Code Generation,Function Factory,PowerShell,Python

Reading Managing Records in Python 

For many years there was no record type in the Python language […] Guido never considered that request […] "in real life you always need to add methods to your data, so just use a custom class"

In PowerShell you can create property bags two ways, Add-Member and Select-Object. Often you need a function that takes parameters and returns an object to hold some data.  Typing this out takes time, tweaking and testing.

Below, New-Function generates your function. This example creates a function named New-Pair that takes two parameters, item1 and item2.

Notice the next line uses the newly created function.

New-Function 'New-Pair' 'item1 item2'            

New-Pair 1 2 | Format-Table -AutoSize

image 

Another Example

New-Function creates a PowerShell function so parameter binding works too.

New-Function `
  'New-Person' 'FirstName LastName Address City State Zip'            

New-Person John Doe -Zip 10001

image

The Factory

Function New-Function ($name, $properties) {
    $parts = $properties.trim().split(' ')
    $parts |
        %{
            $selectProperties += @"
 @{
            Name = '$_'
            Expression = {`$$_}
        },
"@
        }            

# simple way to remove the trailing comma        
$selectProperties = $selectProperties -Replace ",$", ""            

Invoke-Expression @"
Function Global:$name {
param(`$$($parts -join ',$'))

New-Object PSObject |
    select $selectProperties
}
"@
}

Grab The Code

{ 2 comments… read them below or add one }

qa_warrior 09.16.09 at 9:53 pm

You could simplify by taking an object array as second param and get away from the split method.

Doug Finke 09.17.09 at 10:42 am

Good point, I modeled the Python approach. I’ll re-work it for a cleaner PowerShell version.

function ql {$args}

New-Function ‘New-Person’ ( ql FirstName LastName Address City State Zip )

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>