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)
Sign up to request clarification or add additional context in comments.

Comments

-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 Comments

Can you include the part of the article that is relevant to the question into your answer? I actually cannot see how it's related.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.