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 ?
A function in PowerShell is declared with the function keyword followed by the function name and then an open and closing curly brace. The code that the function will execute is contained within those curly braces. The function shown is a simple example that returns the version of PowerShell.
The Invoke-Command cmdlet runs commands on a local or remote computer and returns all output from the commands, including errors. Using a single Invoke-Command command, you can run commands on multiple computers. To run a single command on a remote computer, use the ComputerName parameter.
For this, open your Windows PowerShell ISE and create a new file. The function keyword is used to declare a function in PowerShell, followed by the function name and curly braces. The function's code or body is within those curly braces { }. We will execute this “Get-Version” function at run time.
The Invoke-Expression cmdlet evaluates or runs a specified string as a command and returns the results of the expression or command. Without Invoke-Expression, a string submitted at the command line is returned (echoed) unchanged. Expressions are evaluated and run in the current scope.
Runs commands or expressions on the local computer. The Invoke-Expression cmdlet evaluates or runs a specified string as a command and returns the results of the expression or command. Without Invoke-Expression, a string submitted at the command line is returned (echoed) unchanged. Expressions are evaluated and run in the current scope.
Without Invoke-Expression, the expression is printed, but not evaluated. The first command assigns a value of Get-Process (a string) to the $Command variable. The second command shows the effect of typing the variable name at the command line. PowerShell echoes the string. The third command uses Invoke-Expression to evaluate the string.
String functions are an integral part of PowerShell and there are various functions present to handle the string manipulation related tasks. In PowerShell, everything is an object and string is also an object of type System. String.
You can do this:
&"MyFunctionName" $arg1 $arg2
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With