PSCmdlet动态自动完成一个参数(如Get-Process)

dhc*_*cgn 2 c# powershell pscmdlet

在powershell中,某些参数具有动态自动完成行为.例如,Get-Process参数Name.我可以使用TAB迭代我的所有进程.

Powershell自动完成参数

我想在我的PSCmdlet中使用此行为.

但问题是,我只知道如何使用静态自动完成值来做到这一点.看例子:

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

这是一个如何使用原生powershell http://blogs.technet.com/b/heyscriptingguy/archive/2014/03/21/use-dynamic-parameters-to-populate-list-of-printer-names完成此操作的示例. ASPX


它适用 于@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;
}
Run Code Online (Sandbox Code Playgroud)

bou*_*err 8

来自MSDN:如何声明动态参数

您的Cmdlet类必须实现该IDynamicParameters接口.这个界面:

为cmdlet提供一种机制,以检索可由Windows PowerShell运行时动态添加的参数.

编辑:

IDynamicParameters.GetDynamicParameters()方法应该:

返回具有属性和字段的对象,这些属性和字段具有与cmdlet类或RuntimeDefinedParameterDictionary对象中定义的属性类似的参数相关属性.

如果您查看此链接,作者将在PowerShell中执行此操作.他在运行时创建:

  • ValidateSetAttribute带有可能值的运行时数组的新实例
  • 然后他创造了一个RuntimeDefinedParameter他指定的东西ValidateSetAttribute
  • 他返回RuntimeDefinedParameterDictionary包含此参数的内容

您可以在C#中执行相同的操作.您的GetDynamicParameters()方法应该返回RuntimeDefinedParameterDictionary包含相应的方法RuntimeDefinedParameter.