Class methods with optional parameter?

Is there a way to define class methods with optional parameters?

I tried it with something like this:


class TextLogger {
[void]AddHeader([PSCustomObject]$InputObject, [bool]$Force = $false) {


$MyLogger = [TextLogger]::new()
$MyLogger.AddHeader(‘#### New Script Run ####’)

It throws with missing arguments for $Force…

Try following:

[void]AddHeader([PSCustomObject]$InputObject, [switch]$Force)

Normally a switch is supposed to be $false when not specified in the command line.

I tried it with [bool] and [switch] type. Unfortunately it didn’t work :frowning:


As far as I know, you can’t use optional parameters with classes in PowerShell.

You need to initialize multiple constructors with and without parameters.

Hope this link will help you, last time @kvprasoon shared this link in some other post.

Thanks for all your help.

If I remember correct, I’ve already read somewhere that optional parameter are not implemented in the 5.10version. - But it should be already prepared in the parser.

So I hoped it works now with version 5.1. or 6…