Jonas
Jonas

Reputation: 186

Default value of mandatory parameter in PowerShell

Is it possible to set a default value on a mandatory parameter in a function?

It works without having it set as an mandatory ...

Ie.

Function Get-Hello {
    [CmdletBinding()]
        Param([Parameter(Mandatory=$true)]
              [String]$Text = $Script:Text
        )
    BEGIN {
    }
    PROCESS {
        Write-Host "$Script:Text"
        Write-Host "$Text"
    }
    END {
    }
}

$Text = "hello!"

Get-Hello

Reason for asking this is because i have a function that has some required parameters and the function works perfect with calling it with the required parameters but i also want to make it possible for these variables to be defined in the scripts that use this function in a "better presentable & editable" way along with the function to be able to be run with defining the required parameters.

Hence if defined in the script scope it should take that as default else it should prompty for the value.

Thanks in Advance,

Upvotes: 2

Views: 4844

Answers (1)

user4003407
user4003407

Reputation: 22102

If you targeting to PowerShell V3+, then you can use $PSDefaultParameterValues preferences variable:

$PSDefaultParameterValues['Get-Hello:Text']={
    if(Test-Path Variable::Script:Text){
        # Checking that variable exists, so we does not return $null, or produce error in strict mode.
        $Script:Text
    }
}

Upvotes: 5

Related Questions