5

一連の高度な機能を動的に構築することを検討しています。これには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 と属性のコレクションを使用して新しい関数を生成できるかどうか疑問に思っています。

一部の準疑似コードは次のようになります。私が構築しようとしている (と思う) 2 つの重要な関数は、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

私は完全に間違った木を吠えていますか? これを行う他の方法がいくつかある場合、私は可能性を広く開いています。

4

1 に答える 1

3

その場で関数を作成するために、関数を定義する文字列を作成し、Invoke-Expression を呼び出してコンパイルし、関数プロバイダーに追加します。私の意見では、これはオブジェクト モデルに取り組むよりも強力です。

$f1 = @" function New-Motor() { "これは私の新しいモーターです" } "@

呼び出し式 $f1

于 2009-06-21T19:53:07.673 に答える