I'm working on a method within a class in PowerShell, not a standard function. The method looks like this:
static [void]DisplayLog([string]$message, [MessageType]$type, [MessageAction]$action) {
.....
}
Ideally, I'd like to set a default value for one of the parameters, for example, since not every log display will require an action, I want to set the Enum parameter to 'Continue' by default. Is this possible?
Thanks in advance!
2 Answers
Unfortunately, you can’t set default values for method parameters in PowerShell classes. The typical workaround is to define multiple overloads for your method. For instance, you can create a simpler version of your method that only takes the message and type parameters, and call the main one with the default action. Here's how that would look:
class YourType
{
static [void] DisplayLog([string]$Message, [MessageType]$Type)
{
[YourType]::DisplayLog($Message, $Type, [MessageAction]::ContinueProgram)
}
static [void] DisplayLog([string]$Message, [MessageType]$Type, [MessageAction]$Action)
{
// Your code here
}
}
Just a heads up, there's documentation you might find useful, specifically about the limitations of methods in PowerShell classes. It mentions that method parameters can't have default values at all, which is a known limitation. Until PowerShell provides a feature update, the overload approach is generally how these situations are handled.

Thanks for the insight! I’ll check those docs out for more details.