Home > Software engineering >  Powershell call Function with String Variable
Powershell call Function with String Variable

Time:03-27

    function add($n1, $n2){
        return $n1   $n2
    }

    $num1 = 1
    $num2 = 2

    $operand = "add"

    ########################################################################

    # Given the above scenario, please try to make the next line work:

    # $operand $num1 $num2 -> My ATTEMPT to call function via string variable

    add $num1 $num2 # This is what I am trying to achieve with the above line

Please demonstrate how to call the function using the string variable "Operand".

CodePudding user response:

As long as the function has been loaded in memory, the 2 most common ways you could invoke your function, when the function's name is stored in a variable ($operand), would be to either use the call operator &:

& $operand $num1 $num2 # => 3

Or the dot sourcing operator .:

. $operand $num1 $num2 # => 3

You could also use Invoke-Expression (even though not recommended), as long as the expression is wrapped as a string:

Invoke-Expression "$operand $num1 $num2" # => 3

CodePudding user response:

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.
  • Related