在 powershell 中,某些参数具有动态自动完成行为。 例如,Get-Process 参数名称。我可以使用 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<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;
}
最佳答案
来自 MSDN:How to Declare Dynamic Parameters
您的 Cmdlet
类必须实现 IDynamicParameters
接口(interface)。这个界面:
Provides a mechanism for a cmdlet to retrieve parameters that can be added dynamically by the Windows PowerShell runtime.
编辑:
IDynamicParameters.GetDynamicParameters()
方法应该:
return an object that has properties and fields with parameter related attributes similar to those define in a cmdlet class or a RuntimeDefinedParameterDictionary object.
如果你看这个link ,作者是在 PowerShell 中这样做的。他在运行时创建:
ValidateSetAttribute
的新实例,带有一个运行时可能值数组- 然后,他创建了一个
RuntimeDefinedParameter
,并为其分配了ValidateSetAttribute
- 他返回一个包含这个参数的
RuntimeDefinedParameterDictionary
您可以在 C# 中执行相同的操作。您的 GetDynamicParameters()
方法应返回此 RuntimeDefinedParameterDictionary
,其中包含适当的 RuntimeDefinedParameter
。
关于c# - PSCmdlet 动态自动完成参数(如 Get-Process),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25823910/