是否可以向 Powershell 添加键盘快捷键?

Is it possible to add a keyboard shortcut to Powershell?

在 bash 几十年后,我已经切换到 Powershell,并且在对我的个人资料进行一些配置(并添加 PSCX、openssl 和其他一些工具)之后,我总体上很高兴。

我想念 bash 的一件事:

mkdir some-very-long-dir-name
cd (hit ESC then hit _ on the keyboard)

转义下划线是 bash for 'last item on the previous command'。它非常有用 - 在这个追逐过程中,我不必输入很长的目录名称。

是否可以为 powershell 添加键盘快捷键?怎么样?

如果需要的话,我正在使用 ConEmu 作为我的终端。

简答:

 Set-PSReadlineKeyHandler -Key 'Escape,_' -Function YankLastArg

更长的解释:

感谢@davidbrabant 和@TheIncorrigible1 指出 PSReadLine:它本身不是答案,但理解 PSReadLine 的工作原理是解决这个问题的关键。

虽然 vi 是每个 Linux 发行版的默认编辑器,但 bash 的默认编辑模式是 emacs。来自 the bash docs:

In order to switch interactively between emacs and vi editing modes, use the ‘set -o emacs’ and ‘set -o vi’ commands (see The Set Builtin). The Readline default is emacs mode.

这意味着'escape underscore'来自emacs。

奇怪的是,PSReadLine 与 bash 不同,默认情况下不使用 emacs 模式。来自 the PSREADLine docs:

To use Emacs key bindings, you can use: Set-PSReadlineOption -EditMode Emacs

这不是很明确,但这意味着另一种模式是默认的。确认 运行ning:

get-PSReadlineOption

Returns:

EditMode                               : Vi

所以有两种解决方法:

解决方案 1:更改模式

Set-PSReadlineOption -EditMode Emacs

您可以看到 Get-PSReadlineKeyHandler 的效果包括标准转义下划线快捷方式:

Escape,_         YankLastArg                   Copy the text of the last argument to the input

转义下划线现在有效。

解决方案 2:将快捷方式添加到现有模式

除了改变模式(原来我喜欢 vi 键绑定!),你也可以 运行:

 Set-PSReadlineKeyHandler -Key 'Escape,_' -Function YankLastArg

将其添加到您现有的模式。

ESC+_ 解决方案的替代方案,PowerShell 自动变量 $$ 包含相同的信息,而不需要 PSReadLine(v5.0 之前或没有安装的模块)。

PS C:\> Get-ChildItem -Path 'C:\'

...

PS C:\> $$

C:\

您还可以捕获与 $^ 变量一起使用的命令:

PS C:\> $^

get-childitem