【问题标题】:How to Go To Implementation in PowerShell ISE如何在 PowerShell ISE 中进行实施
【发布时间】:2017-12-15 10:50:50
【问题描述】:

当 PowerShell 脚本位于多个文件中时,很难理解要在哪个文件中搜索特定功能的实现。怎样才能快速去执行某个特定的功能进行编辑?如果在 PowerShell ISE 中将光标放在函数上并通过快捷方式转到函数的实现 - 这将是最好的解决方案。

此命令返回文件路径:

${Function:Verb-MyCommand}.File

然后我可以在这个文件中搜索函数的名称。

但是很慢

【问题讨论】:

    标签: powershell powershell-ise code-navigation


    【解决方案1】:

    您需要在 PowerShell ISE 中运行此代码。附加组件将使用快捷键“CTRL + Alt + SHIFT + B”添加。如果将光标放在脚本编辑器中的函数上并按“CTRL + Alt + SHIFT + B”或从菜单中的附加组件列表中选择 - 所需文件将在 PowerShell ISE 中打开,光标将移至这个函数的开头。

    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");
    

    【讨论】:

    • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
    猜你喜欢
    • 2019-02-26
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 2013-03-15
    相关资源
    最近更新 更多