Ten Uy
Ten Uy

Reputation: 131

Missing an argument for parameter on PS1

I was trying to figured out how can I throw exception or set it to default value, once I didn't put any value on the parameter?

Function ConnectionStrings {

   param(
    [Parameter(
    Mandatory = $false)]

        [AllowNull()]
        [AllowEmptyString()]
    [string] $region 
   )

   try{

    if (!$regionHash.ContainsKey($region)){
        $regionHash["US"]
    } elseif (!$region) {
        $regionHash["US"]
        #$slave = $regionHash["US"].slave
        #$master =  $regionHash["US"].master
        #$track =  $regionHash["US"].tracking
    } else {
        $regionHash[$region]
        #$slave = $regionHash[$region].slave
        #$master =  $regionHash[$region].master
        #$track =  $regionHash[$region].tracking
    }
   } catch {
       Write-Warning -Message "OOPS!"
   }

 }

Once I run the command: ConnectionStrings -region It should throw an exception or set to a default value instead.

Need your guidance, I'm just new on powershell.

Thanks.

edit: Without setting the value of the parameters ConnectionStrings -region

Upvotes: 1

Views: 10379

Answers (1)

FoxDeploy
FoxDeploy

Reputation: 13537

You cannot use both Mandatory and a default value for the same parameter. Why not? If a Param has the Mandatory` attribute, the cmdlet will prompt the user for a value, if no value is provided.

If you want to use a default value, provide one like this:

function Verb-Noun
{
    Param
    (
        # Param1 help description        
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]        
        $Param1 = 'default'
    )
   "value of `$param1` is $Param1"
}

If executed like so

>Verb-Noun -Param1 a
value of $param1 is a

But if the user does not provide a value for the parameter, the default value will be used.

Verb-Noun
value of $param1 is default

Now, if we add the Mandatory attribute like so...


Param
    (
        # Param1 help description
        [Parameter(Mandatory=$true)]   
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]        
        $Param1 = 'default'
    )
#rest of code...

When the user fails to provide a value for Param1, the user is prompted to provide a value. There is no opportunity for the default to be used.

Verb-Noun 
cmdlet Verb-Noun at command pipeline position 1
Supply values for the following parameters:
Param1: 
#function pauses and won't run until a value is provided

Upvotes: 4

Related Questions