在 PowerShell 中按名称调用带有可选参数的 .NET 方法

Mar*_*ryl 5 .net powershell

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

void Method(int one, int two, int three = 0, int four = 0, int five = 0);
Run Code Online (Sandbox Code Playgroud)

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

在 C# 中,我可以这样做:

instance.Method(1, 2, five: 5);
Run Code Online (Sandbox Code Playgroud)

PowerShell 是否有类似的语法?

Mat*_*sen 7

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)
Run Code Online (Sandbox Code Playgroud)