Get definition of function and echo the code

19

2

I've defined a dynamic function in powershell, like this:

> function test { dir -r -fil *.vbproj | ft directory, name }

Then I can just type test and run that function, piping it to other commands, etc. Pretty handy.

Is there a way I can get the definition of the command? Can I echo out the code for my function test? (Without having to go back through my history to where I defined it?)

Jeff B

Posted 2012-04-18T18:48:39.830

Reputation: 1 689

Answers

22

For a function called test:

$function:test

Or if the function name contains a hyphen (eg. test-function):

${function:test-function}

Alternatively:

(Get-Command test).Definition

Indrek

Posted 2012-04-18T18:48:39.830

Reputation: 21 756

5

(Get-Command Test).Definition

That is how I normally get definitions.

EBGreen

Posted 2012-04-18T18:48:39.830

Reputation: 7 834

1In $profile function def ($funcname) { (Get-Command $funcname).Definition } – Kolob Canyon – 2017-02-21T22:33:32.067

3

The current answers will only work for functions that have been created locally. You can, for example, see the definition of native functions like Get-EventLog.

For a list of all the available functions, you can run:

Get-ChildItem Function::

Any of these can be passed into ${function:myFn} or (Get-Command myFn).Definition

If you want to peek at native functions, you can run this code:

$metadata = New-Object system.management.automation.commandmetadata (Get-Command Get-EventLog)
[System.management.automation.proxycommand]::Create($MetaData) | out-file C:\Get-EventLog.ps1

KyleMit

Posted 2012-04-18T18:48:39.830

Reputation: 3 308