Reputation: 202474
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?
Upvotes: 6
Views: 2344
Reputation: 174690
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)
Upvotes: 8
Reputation: 1
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
Upvotes: -4