Mandatory powershell parameter with default value

I am looking for a way to get a PowerShell script to request a parameter that should be required, but shown with a default value, for example:

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

I want to request input, but provide some default values.

If I use the required parameter, it requests the values, but does not show the default value or processes the given value. Unless I make it mandatory, PowerShell does not query the value at all.

Here are some sample scripts I tried:

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

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

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

This script does not request the first parameter, but processes the default value.

+10
3

, :

    [CmdletBinding()]
    Param(
        $SqlServiceAccount = (Read-Host -prompt "SqlServiceAccount ($($env:computername + "_sa"))"),
        $SqlServiceAccountPwd = (Read-Host -prompt "SqlServiceAccountPwd")
    )
    if (!$SqlServiceAccount) { $SqlServiceAccount = $env:Computername + "_sa" }
    ...
+5

, , powershell .

( ), (Read-Host, , - ).

+3

: . , PowerShell , . , , "" , . ( - ) , , , , :

function foo {
    param (
        [Parameter(Mandatory = $true)]
        [Alias('Parameter1')]
        [AllowNull()]
        ${Parameter1[default value]},
        [Parameter(Mandatory = $true)]
        [Alias('Parameter2')]
        [AllowNull()]
        ${Parameter2[1234]}
    )
    $Parameter1 = 
        if (${Parameter1[default value]}) {
            ${Parameter1[default value]}
        } else {
            'default value'
        }
    $Parameter2 = 
        if (${Parameter2[1234]}) {
            ${Parameter2[1234]}
        } else {
            1234
        }
    [PSCustomObject]@{
        Parameter1 = $Parameter1
        Parameter2 = $Parameter2
    }
}

When called without parameters, the function will present the user with an invitation corresponding to the parameter names. When called with -Parameter1 notDefaultValueand / or with -Parameter2 7, aliases will enter and assign the passed value to the selected parameter. Since the variables so named are not suitable for work, it makes sense to assign a value (by default or passed by the user) to a variable that corresponds to the name of the alias / fake parameter.

+3
source

Source: https://habr.com/ru/post/1656835/


All Articles