Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell mandatory parameter with default value shown

I am looking for a way to have an PowerShell script ask for an parameter which needs to be mandatory, but shown with an default value, e.g.:

    .\psscript
    Supply values for the following parameters:
    parameter1[default value]:
    parameter2[1234]:

I want to ask for input but provide some default values.

If I use the mandatory option it asks for the values nicely but doesn't show the default value or process the given value. If I don't make it mandatory then PowerShell doesn't ask for the value at all.

Here's some script examples I tried:

    [CmdletBinding()]
    Param(
        [parameter(Mandatory=$true)] $SqlServiceAccount = $env:computername + "_sa",
        [parameter(Mandatory=$true)] $SqlServiceAccountPwd
    )

This script asks for parameters but does not show or process the default value if I just press enter on the first parameter.

    [CmdletBinding()]
    Param(
        [parameter(Mandatory=$false)] $SqlServiceAccount = $env:computername + "_sa",
        [parameter(Mandatory=$true)] $SqlServiceAccountPwd
    )

This script doesn't ask for the first parameter, but processes the default value.

like image 632
Alex Flora Avatar asked Oct 05 '16 15:10

Alex Flora


People also ask

How do you set a default value to a parameter in PowerShell?

You can use a script block to specify different default values for a parameter under different conditions. PowerShell evaluates the script block and uses the result as the default parameter value. The Format-Table:AutoSize key sets that switch parameter to a default value of True.

How do you make parameters mandatory in PowerShell?

To make a parameter mandatory add a "Mandatory=$true" to the parameter description. To make a parameter optional just leave the "Mandatory" statement out. Make sure the "param" statement is the first one (except for comments and blank lines) in either the script or the function.

What is param () in PowerShell?

The PowerShell parameter is a fundamental component of any script. A parameter is a way that developers enable script users to provide input at runtime. If a PowerShell script's behavior needs to change in some way, a parameter provides an opportunity to do so without changing the underlying code.


1 Answers

Here's a short example that might help:

    [CmdletBinding()]
    Param(
        $SqlServiceAccount = (Read-Host -prompt "SqlServiceAccount ($($env:computername + "_sa"))"),
        $SqlServiceAccountPwd = (Read-Host -prompt "SqlServiceAccountPwd")
    )
    if (!$SqlServiceAccount) { $SqlServiceAccount = $env:Computername + "_sa" }
    ...
like image 68
Burt_Harris Avatar answered Sep 30 '22 18:09

Burt_Harris