【问题标题】:PowerShell MetaProgramming - Generating Advanced FunctionsPowerShell 元编程 - 生成高级函数
【发布时间】:2010-10-30 16:51:15
【问题描述】:

我正在研究动态构建一堆高级功能。为此,我一直在使用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
      }
    } 

我想知道是否可以使用 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

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

【问题讨论】:

  • 我能看到这里唯一缺少的是一旦你添加了参数,你打算用它们做什么?除非你能够修改函数,或者你的函数遍历参数和值的集合......
  • 我不完全确定流程将如何工作。我在想我会先创建函数 Definiton,然后将参数添加到函数中。在我的假代码中,我创建了一个函数,该函数的值使用我稍后将附加的变量作为参数。

标签: powershell metaprogramming powershell-2.0


【解决方案1】:

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

$f1 = @" 函数新电机() { “这是我的新马达” } "@

调用表达式 $f1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    相关资源
    最近更新 更多