PowerShell MetaProgramming - creating advanced features

I am looking at dynamically creating a bunch of advanced features. I used New-PSScript for this, but it does not allow to use all the flexibility that I am looking for.

I read the man page on advanced function parameters and saw something about dynamic parameters at the end of the help article, which gives the following code example

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

      DynamicParam
      {
        if ($path -match "*HKLM*:")
        {
          $dynParam1 = new-object 
            System.Management.Automation.RuntimeDefinedParameter("dp1",
            [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]
          $attributeCollection.Add($attributes)

          $paramDictionary = new-object 
            System.Management.Automation.RuntimeDefinedParameterDictionary
          $paramDictionary.Add("dp1", $dynParam1)

          return $paramDictionary
        } End if
      }
    } 

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

Some semi-pseudo-codes may look like this. The two key functions that I (think) I'm 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 the wrong tree? If there are other ways to do this, I am widely open to opportunities.

+3
1

" ", , , Invoke-Expression . , , , .

$f1 = @" New-Motor() {    " " } "@

$f1

+3

Source: https://habr.com/ru/post/1709598/


All Articles