PSCmdlet动态自动完成一个参数(如Get-Process)
在powershell中,某些参数具有动态自动完成行为。 例如,Get-Process参数Name。 我可以使用TAB迭代我的所有进程。
我想在我的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
。
- JSON .Net在反序列化时不尊重PreserveReferencesHandling
- MySQL连接错误,我从未见过
- ServiceStack – 有没有办法强制所有序列化日期使用特定的DateTimeKind?
- Fisher-Yates在单个字符串上进行洗牌而不是使用相等长度的排列?
- 你怎么看到在LINQ to SQL中的SubmitChanges上导致错误的sql?
- 在按钮单击时重定向新选项卡。(Response.Redirect)在asp.net C#中
- WebBrowser控件和Adobe Flash内容
- 为ASP.Net Web API生成JSON模式
- Fancybox – ASP.NET按钮不起作用