c# - PSCmdlet 动态自动完成参数(如 Get-Process)

标签 c# powershell powershell-cmdlet

在 powershell 中,某些参数具有动态自动完成行为。 例如,Get-Process 参数名称。我可以使用 TAB 遍历所有流程。

Powershell auto complete parameter

我想在我的 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/

相关文章:

c# - 以编程方式在 C# 中将 SSRS 报告保存为 PDF

.net - 如何检查一个路径是否是另一个路径的子代?

PowerShell Get-Service 返回结果很慢

c# - 从 C# 调用 Powershell 函数

c# - 如何在解决方案输出路径中包含来自构建的 dacpac 文件

c# - 测试失败时执行代码

powershell - 在powershell中隐藏标题栏

powershell - 术语 'xsd' 未被识别为 cmdlet、函数、脚本文件或可操作程序的名称

windows - 净用户 $userName/domain

c# - 在 C# 中使用 Indexof 提取字符串