在 powershell 中,某些参数具有动态自动完成行为。
例如,获取-处理参数名称。我可以使用 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 http://blogs.technet.com/b/heyscriptingguy/archive/2014/03/21/use-dynamic-parameters-to-populate-list-of-printer-names.aspx
It works谢谢@bouvirr
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:如何声明动态参数 https://learn.microsoft.com/en-us/powershell/scripting/developer/cmdlet/how-to-declare-dynamic-parameters
Your Cmdlet
类必须实现IDynamicParameters
界面。这个界面:
为 cmdlet 提供一种机制来检索可由 Windows PowerShell 运行时动态添加的参数。
EDIT:
The IDynamicParameters.GetDynamicParameters()
方法应该:
返回一个对象,该对象具有与参数相关的属性和字段,这些属性与 cmdlet 类或 RuntimeDefinedParameterDictionary 对象中定义的属性类似。
如果你看这个link https://martin77s.wordpress.com/2014/06/09/dynamic-validateset-in-a-dynamic-parameter/,作者是在 PowerShell 中这样做的。他在运行时创建:
- 的一个新实例
ValidateSetAttribute
with a runtime可能值的数组
- 然后他创建了一个
RuntimeDefinedParameter
他将其分配给ValidateSetAttribute
- 他返回一个
RuntimeDefinedParameterDictionary
包含该参数的
您可以在 C# 中执行相同的操作。你的GetDynamicParameters()
方法应该返回这个RuntimeDefinedParameterDictionary
含有适当的RuntimeDefinedParameter
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)