1

Is it possible in PowerShell (or even better in PowerShell Core) to bind a function to a parameter ValidateSet specified to the script?

I want to bind the parameter options a, b and c to the functions a_function b_function and c_function to the variable $firstcmd or $secondcmd . Therefore if the script is called by

PS C:\ script.ps1 a

the function a is run.

if the script is called by

PS C:\ script.ps1 a b

the functions a and b are run.

The parameter definition at script start looks like this:

param([Parameter(Mandatory=$false)][String][ValidateSet('a',
                                                        'b',
                                                        'c')$firstcmd,
      [Parameter(Mandatory=$false)][String][ValidateSet('a',
                                                        'b', 
                                                        'c')$secondcmd,
     )

function a_function {
    Write-Host "Hello a"
}

function b_function  {
    Write-Host "Hello b"
}

function c_function  {
    Write-Host "Hello c"
}

# here the "command option to function mapping" magic should happen

1 Answer 1

3

It can be solved by a Switch statement to call a specific function but I think what you are looking for is a more elegant lookup. One possible option is a hash table + the call operator (&):

param([Parameter(Mandatory=$false)][String][ValidateSet('a',
                                                        'b',
                                                        'c')] $firstcmd,
      [Parameter(Mandatory=$false)][String][ValidateSet('a',
                                                        'b', 
                                                        'c')] $secondcmd
     )

function a_function {
    Write-Host "Hello a"
}

function b_function  {
    Write-Host "Hello b"
}

function c_function  {
    Write-Host "Hello c"
}

#hash table:
$ParamToFunction = @{
    a = "a_function"
    b = "b_function"
    c = "c_function"
}

#function calls:
& $ParamToFunction[$firstcmd]
& $ParamToFunction[$secondcmd]

Of course it will throw an error if you don't provide a value for any parameter - I leave it to you to handle such cases.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks exactly what I wanted. Additionally I wrapped the function calls in if ($firstcmd) { & $ParamToFunction[$firstcmd] }, because my parameters are not mandatory.
is it also possible to pass an argument to that table?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.