Home > Mobile >  How to get powershell function source with full header
How to get powershell function source with full header

Time:08-14

As seen here https://superuser.com/questions/414036/get-definition-of-function-and-echo-the-code this would get the body of test-function

${function:test-function}

but not the header of test-function with parameters

CodePudding user response:

You'll have to add the missing parts yourself (function <name> { ... }) in order to form a full function definition:

$funcDef = "function test-function { ${function:test-function} }"

If you're given the function name in a variable or you want to avoid repeating the function name:

$funcName = 'test-function'

$funcDef = "function $funcName { $(Get-Content function:$funcName) }"

Note that the function body returned does include parameters, in the form of a param(...) block - even if the original definition used the in-line parameter-declaration form. E.g., both function test-function($foo) { 'foo' } and function test-function { param($foo) 'foo' } result in body param($foo) 'foo' (with variations in whitespace).


Background:

${function:test-function} is an instance of namespace variable notation, and therefore only works with literal names.

It returns the body of the specified function as a script block, which when stringified, results in the block's verbatim source code (without the { and } that you use to create a script-block literal.

Get-Content function:test-function is what the namespace variable notation translates into, except that the cmdlet-based enables use of variables in its arguments.

  • Related