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

在powershell中,某些参数具有动态自动完成行为。 例如,Get-Process参数Name。 我可以使用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

 public string[] Tables { get; set; } public object GetDynamicParameters() { if (!File.Exists(Path)) return null; var tableNames = new List(); 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() { new ParameterAttribute(), new ValidateSetAttribute(tableNames.ToArray()) })); return runtimeDefinedParameterDictionary; } 

从MSDN: 如何声明动态参数

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

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

编辑:

IDynamicParameters.GetDynamicParameters()方法应该:

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

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

  • ValidateSetAttribute的新实例,带有可能值的运行时数组
  • 然后,他创建一个RuntimeDefinedParameter在其上分配ValidateSetAttribute
  • 他返回包含此参数的RuntimeDefinedParameterDictionary

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