Home > front end >  Pass through user parameter and fallback to default
Pass through user parameter and fallback to default

Time:12-31

How do I fallback to default value inside a subroutine? Consider having 1.ps1 as follows:

param(
    [Parameter(Mandatory)]
    [ValidateNotNullOrEmpty()]
    [ValidateSet('A', 'B')]
    [String]
    $What,

    $Target
)

function CallA {
   param(
       $Target = 'default for A'
   )

   Write-Host $Target
}

function CallB {
   param(
       $Target = 'default for B'
   )

   Write-Host $Target
}

&"Call$What" -Target $Target

If I call it from powershell console like so: ./1 -What A I'll get empty line, whereas the intention would be to get default for A as the result.

I could of course check if $Target is $null in each function but I find this way being cumbersome. Is there a better way except for explicit check?

CodePudding user response:

Use splatting - conditionally add the -Target parameter value to a dictionary and pass that to the inner function call with the @ splat operator:

param(
    [Parameter(Mandatory)]
    [ValidateNotNullOrEmpty()]
    [ValidateSet('A', 'B')]
    [String]
    $What,

    $Target
)

function CallA {
   param(
       $Target = 'default for A'
   )

   Write-Host $Target
}

function CallB {
   param(
       $Target = 'default for B'
   )

   Write-Host $Target
}

# Create a dictionary to hold the parameter arguments we want to "splat"
$callParams = @{}

# Conditionally add parameter arguments to the dictionary
if($PSBoundParameters.ContainsKey('Target')){
  # -Target argument was passed, pass it on to in inner function call
  $callParams['Target'] = $Target
}

# Call function with splatted arguments
&"Call$What" @callParams

CodePudding user response:

When invoking your script, either use

./1 -What A -Target A

or

within your script, correctly initialise $Target with what is passed via -What

param(
    [Parameter(Mandatory)]
    [ValidateNotNullOrEmpty()]
    [ValidateSet('A', 'B')] [String]$What,
    $Target
)

# Using ./1 -What A will not populate $Target unless you do $Target = $What
"`$Target=$Target, `$What=$What"

## your functions etc ...

# $Target is still blank
&"Call$What" -Target $Target
  • Related