How to Go To Implementation in PowerShell ISE

607 views Asked by At

When PowerShell scripts are in several files, it is difficult to understand in which file you want to search for the implementation of a particular function. How can I quickly go to the implementation of a specific function for editing? If in PowerShell ISE put the cursor on the function and by shortcut go to the implementation of the function - this would be the best solution.

This command return file path:

${Function:Verb-MyCommand}.File

Then I can do a search for the name of the function in this file.

But it's very slow

1

There are 1 answers

1
vovkas On BEST ANSWER

You need to run this code in PowerShell ISE. Add-On will be added with the shortcut "CTRL + Alt + SHIFT + B". If you place the cursor on the function in the script editor and press "CTRL + Alt + SHIFT + B" or select from the Add-Ons list in the menu - the required file will open in PowerShell ISE and the cursor will move to the beginning of this function.

function Get-TokenInfo
{
  [Alias("ti")]
  [OutputType([System.Management.Automation.PSToken[]])]
  Param()
  Process
  {
    $editor = $psise.CurrentFile.Editor;
    $line = $editor.CaretLine;
    $column = $editor.CaretColumn;
    return [system.management.automation.psparser]::Tokenize($psISE.CurrentFile.Editor.Text, [ref]$null) |?{$_.StartLine -le $line -and $_.EndLine -ge $line -and $_.StartColumn -le $column -and $_.EndColumn -ge $column};
 }
}
function GoTo-CommandImplementation
{
  [Alias("gti")]
  Param()

  Process
  {
    $commandInfo = ti |?{$_.Type -eq [System.Management.Automation.PSTokenType]::Command} | select -First 1;
    if(!$commandInfo) 
    {
        Write-Host "Is not a command";
    }
    else
    {
        $commandName = $commandInfo.Content;
        $command = Get-Command $commandName;
        if($command -is [System.Management.Automation.AliasInfo])
        {
            $command = $command.ResolvedCommand;
        }
        if($command.CommandType -eq [System.Management.Automation.CommandTypes]::Function)
        {
            $functionInfo = [System.Management.Automation.FunctionInfo]$command;
            $commandFile = $functionInfo.ScriptBlock.File;
            $line = $functionInfo.ScriptBlock.StartPosition.StartLine;
            $column = $functionInfo.ScriptBlock.StartPosition.StartColumn;
            psedit $commandFile;
            $psise.CurrentFile.Editor.Focus();
            $psise.CurrentFile.Editor.SetCaretPosition($line, $column);
        }
        else
        {
            Write-Host "Is not Function.";
        }
    }
  }
}
$PowerPSISERoot.Submenus.Add("GoTo Implementation", {gti}, "CTRL+Alt+SHIFT+B");