【问题标题】:Calling .NET method with optional parameter by name in PowerShell在 PowerShell 中按名称调用带有可选参数的 .NET 方法
【发布时间】:2018-10-11 14:04:58
【问题描述】:

我有一个带有许多可选参数的 .NET 类,比如:

void Method(int one, int two, int three = 0, int four = 0, int five = 0);

有没有办法从 PowerShell 调用方法,将值传递给参数 five,而不列出参数 threefour

在 C# 中,我可以做到:

instance.Method(1, 2, five: 5);

有没有类似PowerShell的语法?

【问题讨论】:

    标签: .net powershell


    【解决方案1】:

    PowerShell 没有用于命名可选参数的本机语法,因此我们需要一些反射魔法来完成这项工作。

    基本上,您需要计算命名参数的相应参数索引,然后将带有[type]::Missing 的数组代替您要省略的可选参数传递给MethodInfo.Invoke()

    $method = $instance.GetType().GetMethod("Method") # assuming Method has no additional overloads
    $params = @(1, 2, [type]::Missing, [type]::Missing, 5)
    $method.Invoke($instance, $params)
    

    【讨论】:

      【解决方案2】:

      是的,这是可能的。 Posweshell 建立在 .Net 之上。您可以通过在 Poweshell 中调用构造函数来创建 .Net 类的对象 这是一篇关于如何在 Powershell 中使用 .Net 的文章。

      https://mcpmag.com/articles/2015/11/04/net-members-in-powershell.aspx

      希望对你有帮助

      【讨论】:

      猜你喜欢
      • 2013-07-03
      • 2017-09-02
      • 2013-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 2010-09-22
      • 1970-01-01
      相关资源
      最近更新 更多