To complement Santiago Squarzon's helpful answer, here is a different way that uses a hashtable of script blocks:
$funTable = @{
add = { param($n1, $n2) $n1 + $n2 }
sub = { param($n1, $n2) $n1 - $n2 }
}
Alternatively you can reference functions (which must have been defined before):
$funTable = @{
add = $function:add
sub = $function:sub
}
Now you can call the functions by string variable like this:
$operand = 'add'
& $funTable.$operand $num1 $num2
# Just a different syntax, it's a matter of taste
$funTable.$operand.Invoke( $num1, $num2 )
You may use . instead of &, but in most cases it's not recommended. The difference is that with ., any temporary variable defined by the function will leak into the caller's scope, but you normally want such variables to be removed automatically, which is what & does.
Advantages of using a hashtable:
- Operand functions are logically grouped.
- When the function name is user input, they can't run arbitrary PowerShell code (as would be possible with
& $operand). They are only allowed to run the functions that you store in $funTable. Otherwise they will get an error.