Get definition of function and echo the code
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?)
Solution 1:
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
Solution 2:
(Get-Command Test).Definition
That is how I normally get definitions.
Solution 3:
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?