3

PowerShell では、いくつかのパラメーターが動的なオートコンプリート動作をしています。たとえば、パラメーター Name を Get-Process します。TAB を使用して、すべてのプロセスを繰り返すことができます。

Powershell オートコンプリート パラメーター

この動作を PSCmdlet で使用したいと考えています。

しかし、問題は、静的なオートコンプリート値でこれを行う方法しか知らないことです。例を参照してください。

public class TableDynamicParameters
{
    [Parameter]
    [ValidateSet("Table1", "Table2")]
    public string[] Tables { get; set; }
}

これがネイティブの powershell http://blogs.technet.com/b/heyscriptingguy/archive/2014/03/21/use-dynamic-parameters-to-populate-list-of-printer-namesでどのように行われるかの例を次に示します。 aspx


それ は@bouvierrにthxで動作します

public string[] Tables { get; set; }

public object GetDynamicParameters()
{
    if (!File.Exists(Path)) return null;

    var tableNames = new List<string>();
    if (TablesCache.ContainsKey(Path))
    {
        tableNames = TablesCache[Path];
    }
    else
    {
        try
        {
            tableNames = DbContext.GetTableNamesContent(Path);
            tableNames.Add("All");
            TablesCache.Add(Path, tableNames);
        }
        catch (Exception e){}
    }

    var runtimeDefinedParameterDictionary = new RuntimeDefinedParameterDictionary();
    runtimeDefinedParameterDictionary.Add("Tables", new RuntimeDefinedParameter("Tables", typeof(String), new Collection<Attribute>() { new ParameterAttribute(), new ValidateSetAttribute(tableNames.ToArray()) }));

    return runtimeDefinedParameterDictionary;
}
4

1 に答える 1

9

MSDN から:動的パラメーターを宣言する方法

クラスはインターフェイスCmdletを実装する必要がありIDynamicParametersます。このインターフェイス:

Windows PowerShell ランタイムによって動的に追加できるパラメーターを取得するためのコマンドレットのメカニズムを提供します。

編集:

IDynamicParameters.GetDynamicParameters()メソッドは次のことを行う必要があります。

コマンドレット クラスまたは RuntimeDefinedParameterDictionary オブジェクトで定義されているものと同様のパラメーター関連の属性を持つプロパティとフィールドを持つオブジェクトを返します。

このリンクを見ると、著者は PowerShell でこれを行っています。彼は実行時に以下を作成します。

  • 可能な値のランタイム配列をValidateSetAttribute持つの新しいインスタンス
  • 次に、 を作成し、そのRuntimeDefinedParameter上に を割り当てます。ValidateSetAttribute
  • RuntimeDefinedParameterDictionary彼は、このパラメータを含むを返します

C# でも同じことができます。メソッドは、適切な を含むGetDynamicParameters()this を返す必要があります。RuntimeDefinedParameterDictionaryRuntimeDefinedParameter

于 2014-09-13T15:34:44.683 に答える