tl;博士
我想找到bash
edit-and-execute-command
小部件或zsh
edit-command-line
小部件的 Powershell 版本。
背景
短命令直接在命令行上执行,长而复杂的命令从脚本中执行。但是,在它们变得“长”之前,能够在命令行上测试中等长度的命令会有所帮助。为了帮助完成这项工作,在外部编辑器中编辑命令变得非常有帮助。AFAIK Powershell 并不像 egbash
和zsh
do 那样本机支持这一点。
我目前的尝试
我是 Powershell 的新手,所以我一定会犯很多错误,但我已经提出了一个使用[Microsoft.Powershell.PSConsoleReadLine]
该类功能的可行解决方案。我可以将当前命令行复制到文件中,编辑文件,然后将编辑后的版本重新注入命令行:
Set-PSReadLineKeyHandler -Chord "Alt+e" -ScriptBlock {
$CurrentInput = $null
# Copy current command-line input, save it to a file and clear it
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref] $CurrentInput, [ref] $null)
Set-Content -Path "C:\Temp\ps_${PID}.txt" -Value "$CurrentInput"
[Microsoft.PowerShell.PSConsoleReadLine]::KillRegion()
# Edit the command with gvim
Start-Job -Name EditCMD -ScriptBlock { gvim "C:\Temp\ps_${Using:PID}.txt" }
Wait-Job -Name EditCMD
# Get command back from file the temporary file and insert it into the command-line
$NewInput = (Get-Content -Path "C:\Temp\ps_${PID}.txt") -join "`n"
[Microsoft.PowerShell.PSConsoleReadLine]::Insert($NewInput)
}
问题
我目前的解决方案感觉笨重而且有点脆弱。还有其他解决方案吗?可以改进当前的解决方案吗?
环境
- 操作系统 Windows 10.0.19043.0
- Powershell 版本 5.1.19041.1320
- PSReadLine 版本 2.0.0
我采用的解决方案
创建一个类似于mklement0显示的“烘焙”可执行文件。我更喜欢vim
这个而不是`gvim,因为它直接在控制台中运行:
'@vim -f %*' > psvim.cmd
$env:EDITOR = "psvim"
Set-PSReadLineKeyHandler -Chord "Alt+e" -Function ViEditVisually