23

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?)

3 Answers 3

29

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
7
(Get-Command Test).Definition

That is how I normally get definitions.

1
  • 2
    In $profile function def ($funcname) { (Get-Command $funcname).Definition } Feb 21, 2017 at 22:33
6

Both of these approaches - ${function:myFn} or (Get-Command myFn).Definition - will only work for functions that have been created locally.

You also can see the definition of native functions like Get-EventLog (e.g.). with the CommandMetadata and ProxyCommand commands in the System.Management.Automation namespace like this:

using namespace System.Management.Automation

$cmd = Get-Command Get-EventLog
$meta = New-Object CommandMetadata($cmd)
$src = [ProxyCommand]::Create($meta)
$src | Write-Output

See Also: Can we see the source code for PowerShell cmdlets?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.