PowerShell Mandatory Parameter With Default Value

Rohan Timalsina May 19, 2022
PowerShell Mandatory Parameter With Default Value

The parameter is a fundamental feature of a PowerShell script. They are useful for taking input from users at the script’s runtime.

In PowerShell, parameters are used in scripts and functions by enclosing them in a param block. This tutorial will teach you to show default values in a mandatory parameter in PowerShell.

PowerShell Mandatory Parameter With Default Value Shown

The mandatory parameter does not have the default values in PowerShell. Since parameters can have any names, you can include the default value in the names to show in the mandatory parameters.

Parameters are most commonly used in PowerShell functions. The following is a simple example of using parameters in a function.

function Test {
    param
    (
        $Username = $(Read-Host -Prompt 'Enter your username'),
        $ID = $(Read-Host -Prompt 'Enter your ID')
    )
    "Your username is $Username and ID is $ID."
}
Test

Output:

Enter your username: rhntm
Enter your ID: 123
Your username is rhntm and ID is 123.

In the following example, two mandatory parameters, Username[rhntm] and ID[123], are used where the value in the braces works as the default value.

function Test {
    param (
        [Parameter(Mandatory = $true)]
        ${Username[rhntm]},
        [Parameter(Mandatory = $true)]
        ${ID[123]}
    )
    $Username = if (${Username[rhntm]}) { ${Username[rhntm]} }
    else {
        'rhntm'
    }
    $ID = if (${ID[123]}) {
        ${ID[123]}
    }
    else {
        123
    }
    "Your username is $Username and ID is $ID."

}
Test

Output:

cmdlet Test at command pipeline position 1
Supply values for the following parameters:
Username[rhntm]: sam
ID[123]: 456
Your username is sam and ID is 456.

As you can see, the output exactly looks like what we want to do. If no values are given, it uses the default value.

Output:

cmdlet Test at command pipeline position 1
Supply values for the following parameters:
Username[rhntm]:
ID[123]:
Your username is rhntm and ID is 123.

We hope this article has guided you to show default values in mandatory parameters in PowerShell.

Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

Related Article - PowerShell Parameter