user69453
user69453

Reputation: 1405

Bind PowerShell function to parameter

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

Upvotes: 1

Views: 516

Answers (1)

Dávid Laczkó
Dávid Laczkó

Reputation: 1101

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.

Upvotes: 3

Related Questions