通过String在PowerShell中调用函数

时间:2022-11-25 18:03:26

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

我正在尝试使用字符串“动态”调用Powershell函数。例

$functionToInvoke = "MyFunctionName";

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

Is there any way to achieve this with PowerShell 2.0 ?

有没有办法用PowerShell 2.0实现这一目标?

2 个解决方案

#1


25  

You can do this:

你可以这样做:

 &"MyFunctionName" $arg1 $arg2

#2


9  

If you're wanting to variableize the whlole thing:

如果你想改变这个琐事:

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

$functionToInvoke = "MyFunctionName";


invoke-expression  "$functionToInvoke $arg1 $arg2"

scripts test

#1


25  

You can do this:

你可以这样做:

 &"MyFunctionName" $arg1 $arg2

#2


9  

If you're wanting to variableize the whlole thing:

如果你想改变这个琐事:

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

$functionToInvoke = "MyFunctionName";


invoke-expression  "$functionToInvoke $arg1 $arg2"

scripts test