Skip to content

Instantly share code, notes, and snippets.

@tophatsteve
Created June 7, 2012 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tophatsteve/2888783 to your computer and use it in GitHub Desktop.
Save tophatsteve/2888783 to your computer and use it in GitHub Desktop.
Dymanically generate a function in Powershell
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