Go to Function Definition on F12

by Sep 12, 2013

If you are into writing long and complex PowerShell code with a lot of functions, then this one is for you. In other development environments, when you place the cursor on a function and press F12, the editor takes you to the function definition. PowerShell ISE won't do that.

You can add functionality to ISE, though. The following code adds a new command "Find Definition" to the AddOns menu and assigns a F12 keyboard shortcut to it.

Next time you click on a function inside a lengthy script, ISE takes you directly to the function definition–provided it can be found somewhere inside of that script.

function Find-Definition {
    $e = $psISE.CurrentFile.Editor
    $Column = $e.CaretColumn
    $Line = $e.CaretLine
    $AST = [Management.Automation.Language.Parser]::ParseInput($e.Text,[ref]$null,[ref]$null)
            ($ast -is [System.Management.Automation.Language.CommandAst]) -and
            (($ast.Extent.StartLineNumber -lt $Line -and $ast.Extent.EndLineNumber -gt $line) -or
            ($ast.Extent.StartLineNumber -eq $Line -and $ast.Extent.StartColumnNumber -le $Column) -or
            ($ast.Extent.EndLineNumber -eq $Line -and $ast.Extent.EndColumnNumber -ge $Column))}, $true) |
            Select-Object -ExpandProperty CommandElements |
            ForEach-Object {  
                $name = $_.Value  
                        ($ast -is [System.Management.Automation.Language.FunctionDefinitionAst]) -and
                        ($ast.Name -eq $name)}, $true) |
                        Select-Object -Last 1 |
                        ForEach-Object {

$psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("Goto Definition",{Find-Definition},'F12') 

Twitter This Tip! ReTweet this Tip!