PSCmdlet dynamic auto complete a parameter (like Get-Process)

蓝咒 提交于 2019-12-22 12:33:30

问题


In powershell some parameter have a dynamic auto complete behavior. For Example, Get-Process the parameter Name. I can iterate trough all my processes with TAB.

I want to use this behavior in my PSCmdlet.

But the problem is, I only know how to do this with static auto complete valuee. See the example:

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

Here an example how this is done with native powershell http://blogs.technet.com/b/heyscriptingguy/archive/2014/03/21/use-dynamic-parameters-to-populate-list-of-printer-names.aspx


It works thx to @bouvierr

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;
}

回答1:


From MSDN: How to Declare Dynamic Parameters

Your Cmdlet class must implement the IDynamicParameters interface. This interface:

Provides a mechanism for a cmdlet to retrieve parameters that can be added dynamically by the Windows PowerShell runtime.

EDIT:

The IDynamicParameters.GetDynamicParameters() method should:

return an object that has properties and fields with parameter related attributes similar to those define in a cmdlet class or a RuntimeDefinedParameterDictionary object.

If you look at this link, the author is doing this in PowerShell. He creates at runtime:

  • a new instance of ValidateSetAttribute with a runtime array of possible values
  • He then creates a RuntimeDefinedParameter onto which he assigns the ValidateSetAttribute
  • He returns a RuntimeDefinedParameterDictionary containing this parameter

You can do the same in C#. Your GetDynamicParameters() method should return this RuntimeDefinedParameterDictionary containing the appropriate RuntimeDefinedParameter.



来源:https://stackoverflow.com/questions/25823910/pscmdlet-dynamic-auto-complete-a-parameter-like-get-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!