6

I have a .NET class with number of optional parameters, say:

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

Is there a way to call the method from PowerShell, passing a value to the parameter five, without listing parameters three and four?

In C#, I can do:

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

Is there a similar syntax is PowerShell?

0

2 Answers 2

8

PowerShell has no native syntax for named optional parameters, so we'll need a bit of reflection magic to make this work.

Basically you'll need to count the corresponding parameter index of the named parameters and then pass an array with [type]::Missing in place of the optional parameters you want to omit to 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)
-4

Yes, this is possible. Posweshell is built on top of .Net. you can create an object of .Net class by calling constructor in Poweshell Here is an article on how to use .Net in powershell.

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

Hope this helps

2

Not the answer you're looking for? Browse other questions tagged or ask your own question.