Invoking Function in PowerShell via String

断了今生、忘了曾经 提交于 2019-11-27 14:38:13

问题


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 ?


回答1:


You can do this:

 &"MyFunctionName" $arg1 $arg2



回答2:


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


来源:https://stackoverflow.com/questions/6847923/invoking-function-in-powershell-via-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!