26

I'm trying to Invoke a Powershell function "dynamically" using a string. Example

$functionToInvoke = "MyFunctionName";

Invoke-Function $functionToInvoke $arg1 $arg2  #  <- what I would like to do

Is there any way to achieve this with PowerShell 2.0 ?

2 Answers 2

38

You can do this:

 &"MyFunctionName" $arg1 $arg2
Sign up to request clarification or add additional context in comments.

1 Comment

How would you call a function named start? It seems to get picked up by cmd? Might not be saying that correctly... are there ways around this kind of thing in powershell? or do I just have to name my method differently?
15

If you want to make variables from the whole thing use Invoke-Expression:

function myfunctionname {write-host "$($args[0]) $($args[1])"}
$arg1 = "scripts"
$arg2 = "test"

$functionToInvoke = "MyFunctionName";


Invoke-Expression  "$functionToInvoke $arg1 $arg2"

scripts test

Comments

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.