2011-07-27 29 views
14

我想使用字符串「動態」調用Powershell函數。示例通過字符串在PowerShell中調用函數

$functionToInvoke = "MyFunctionName"; 

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

有沒有什麼辦法可以通過PowerShell 2.0實現?

回答

24

你可以這樣做:

&"MyFunctionName" $arg1 $arg2 
+0

你會如何調用名爲啓動功能?它似乎被cmd拾起?可能不是說得那麼正確......在PowerShell中有這種方法嗎?或者我只需要以不同的方式命名我的方法? – BuddyJoe

8

如果你想variableize的whlole件事:

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

$functionToInvoke = "MyFunctionName"; 


invoke-expression "$functionToInvoke $arg1 $arg2" 

scripts test