获取函数定义并回显代码

Jef*_*f B 22 powershell

我在powershell中定义了一个动态函数,如下所示:

> function test { dir -r -fil *.vbproj | ft directory, name }
Run Code Online (Sandbox Code Playgroud)

然后我可以键入test并运行该函数,将其传递给其他命令等。非常方便。

有没有办法获得命令的定义?我可以回显我的函数的代码test吗?(不必回顾我的历史到我定义它的地方?)

Ind*_*rek 27

对于名为 的函数test

$function:test
Run Code Online (Sandbox Code Playgroud)

或者,如果函数名称包含连字符(例如test-function):

${function:test-function}
Run Code Online (Sandbox Code Playgroud)

或者:

(Get-Command test).Definition
Run Code Online (Sandbox Code Playgroud)


EBG*_*een 7

(Get-Command Test).Definition
Run Code Online (Sandbox Code Playgroud)

这就是我通常获得定义的方式。

  • 在`$profile``function def ($funcname) { (Get-Command $funcname).Definition }` (2认同)

Kyl*_*Mit 5

当前答案仅适用于本地创建的函数。例如,您可以查看本机函数的定义,例如Get-EventLog.

有关所有可用函数的列表,您可以运行:

Get-ChildItem Function::
Run Code Online (Sandbox Code Playgroud)

这些中的任何一个都可以传入${function:myFn}(Get-Command myFn).Definition

如果您想查看本机函数,可以运行以下代码

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