取得函數的定義並回顯程式碼

取得函數的定義並回顯程式碼

我在powershell中定義了一個動態函數,如下所示:

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

然後我可以輸入test並運行該函數,將其傳遞給其他命令等。

有什麼方法可以取得命令的定義嗎?我可以回顯我的函數的程式碼test嗎? (不必回顧我的歷史到我定義它的地方?)

答案1

對於一個名為 的函數test

$function:test

或者,如果函數名稱包含連字符(例如。test-function):

${function:test-function}

或者:

(Get-Command test).Definition

答案2

(Get-Command Test).Definition

這就是我通常獲得定義的方式。

答案3

這兩種方法(${function:myFn}或說(Get-Command myFn).Definition)僅適用於本地建立的函數。

您也可以查看本機函數的定義,例如Get-EventLog(例如)。與CommandMetadataProxyCommand命令在System.Management.Automation像這樣的命名空間:

using namespace System.Management.Automation

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

也可以看看:我們可以查看 PowerShell cmdlet 的原始碼嗎?

相關內容