5

In powershell functions i can have something like

Function myFunction { Param( [Parameter(Mandatory=$True)][string]$foo, [Parameter(Mandatory=$False)][string]$bar = "whatever" ) .... } 

But this seems limited to functions - is there something similar for method?

class MyClass { ... [void]MethodA { Param( .... 

dont works for me.
The interpreter complains about the missing '(' in the class method parameter list.

1 Answer 1

6

Adding methods to classes works just like in most other scripting languages one might know. Instead of [void]MethodA {Param()...} you might want to add a block like described in this blog post or here:

class MyClass { #... [void]MethodA ($param) { #... } } 

As your title says optional parameters (but your question doesn't) a short word on that...

Usually you want multiple signatures for such cases. That means you create a method MethodA($arg1, $arg2) and a delegating method like MethodA($arg1) {MethodA($arg1, $null)}

Sign up to request clarification or add additional context in comments.

2 Comments

And how can I add seriously optional parameter?
@Đonny Optional parameters are, unfortunately, mandatory.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.