Wolfgang
Wolfgang

Reputation: 340

Powershell - Optional parameter in method of a class

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.

Upvotes: 4

Views: 10899

Answers (1)

Clijsters
Clijsters

Reputation: 4256

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)}

Upvotes: 5

Related Questions