PowerShell 元编程 - 生成高级函数

And*_*der 5 powershell metaprogramming powershell-2.0

我正在考虑动态构建一堆高级功能。为此,我一直在使用New-PSScript,但它无法实现我正在寻找的所有灵活性。

我正在阅读有关函数高级参数的手册页,并在帮助文章的末尾看到了有关动态参数的内容,其中提供了以下示例代码

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
      }
    } 
Run Code Online (Sandbox Code Playgroud)

我想知道是否可以使用 RuntimeDefinedParameter 和属性集合来生成新函数。

一些半伪代码可能看起来像这样。我(认为)正在尝试构建的两个关键函数是 New-Parameter 和 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
Run Code Online (Sandbox Code Playgroud)

我是不是完全找错了树?如果有其他一些方法可以做到这一点,我对可能性持开放态度。

tel*_*ine 3

为了动态创建函数,我创建了定义函数的字符串,并调用 Invoke-Expression 对其进行编译并将其添加到函数提供程序。在我看来,这比处理对象模型更强大。

$f1 = @" function New-Motor() { "这是我的新电机" } "@

调用表达式 $f1