Created
June 7, 2012 13:20
-
-
Save tophatsteve/2888783 to your computer and use it in GitHub Desktop.
Dymanically generate a function in Powershell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function GenerateFunction($functionName, $codeBlock) | |
{ | |
$argList = "" | |
foreach($argName in $args) | |
{ | |
if($argList.Length -gt 0) | |
{ | |
$argList += "," | |
} | |
$argList += "`$" + $argName | |
} | |
$newFunc = | |
@" | |
function global:$functionName($argList) | |
{ | |
$codeBlock | |
} | |
"@ | |
Invoke-Expression $newFunc | |
} | |
GenerateFunction myfunc -codeBlock {echo "hello"} | |
# PS> myfunc | |
# hello | |
GenerateFunction myAdd -codeBlock {$a + $b} a b | |
# PS> myAdd 1 2 | |
# 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment