简体   繁体   中英

How to get powershell function source with full header

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

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. Eg, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM