R – PowerShell MetaProgramming – Generating Advanced Functions


I am looking at dynamically building a bunch of Advanced Functions. I have been using New-PSScript for this but it doesn't allow for all the flexibility I am looking for.

I was reading the man page for about functions advanced parameters and saw something about Dynamic Parameters at the end of the help article which gives the following sample code

function Sample {
      Param ([String]$Name, [String]$Path)

        if ($path -match "*HKLM*:")
          $dynParam1 = new-object 
            [Int32], $attributeCollection)

          $attributes = new-object System.Management.Automation.ParameterAttribute
          $attributes.ParameterSetName = 'pset1'
          $attributes.Mandatory = $false

          $attributeCollection = new-object 
            -Type System.Collections.ObjectModel.Collection``1[System.Attribute]

          $paramDictionary = new-object 
          $paramDictionary.Add("dp1", $dynParam1)

          return $paramDictionary
        } End if

I am wondering if I can use the RuntimeDefinedParameter and the collection of attributes to generate new functions.

Some semi-pseudo code might look like this. The two key functions I (think) I am trying to build are New-Parameter and Add-Parameter.

$attributes1 = @{Mandatory=$true;Position=0;ValueFromPipeline=$true}
$param1 = New-Paramater -name foo -attributes $attributes1

$attributes2 = @{Mandatory=$true;Position=1}
$param2 = New-Paramater -name bar -attributes $attributes2

cd function:
$function = new-item -name Get-FooBar -value {"there is a $foo in the $bar"}
Add-Parameter -function $function -paramater $param1,$param2

Am I completely barking up the wrong tree? If there are some other ways to do this I am wide open to possibilities.

Best Solution

In order to create functions on the fly I create the string that defines the function and call Invoke-Expression to compile it and add it to the function provider. This is in my opinion even more powerful than working on the object model.

$f1 = @" function New-Motor() { "This is my new motor" } "@

Invoke-Expression $f1