获取函数定义并回显代码


18

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

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

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

有没有一种方法可以获取命令的定义?我可以回显我的函数的代码test吗?(不必回顾我的历史记录到我定义的位置吗?)

Answers:


21

对于一个名为的函数test

$function:test

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

${function:test-function}

或者:

(Get-Command test).Definition

5
(Get-Command Test).Definition

那就是我通常得到定义的方式。


$profile function def ($funcname) { (Get-Command $funcname).Definition }
Kolob峡谷

3

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

有关所有可用功能的列表,可以运行:

Get-ChildItem Function::

这些都可以传递给${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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.