[SOLVED] Powershell call Function with String Variable

Issue

    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".

Solution

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

Answered By – Santiago Squarzon

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *