power shell 7 autosuggestion 补全设置
通常 Windows 下默认的 power shell 是 5.* 版本的, 但是最新版的 power shell 已经更新到 7.* 版本了, 建议升级体验一下新功能, 其中自动补全等等还是很不错的, 配合 oh my posh, 基本相当于 linux 下 zsh 的体验了。
更新 power shell
查看当前 power shell 版本
$PSVersionTable.PSVersion
不出意外应该显示 5.* 版本。
使用 winget 安装最新版本 power shell
winget install Microsoft.PowerShell
将默认终端改为 power shell 7
打开设置如下修改即可。对于美化 power shell 有需求的读者可以参考我此前的文章。
配置 power shell 7
可以使用文件管理器进入 C:\Users\username\Documents\PowerShell
下,新建文件 Microsoft.PowerShell_profile.ps1
,将此前的配置拷贝进入即可,其中最主要是添加
Set-PSReadLineKeyHandler -Key Tab -Function AcceptSuggestion
将补全建议键设置为 Tab 键,否则默认是右箭头,按起来还是不太方便。
补充
以上的简单配置可以实现Tab进行智能补全,但是当系统中没有历史记录时,Tab键就没有作用了,这时候我们最基础的路径补全被我们 disable 了,也无法使用。以下是我给出的一个折中的方案,当可以使用智能建议时,优先使用智能建议,当没有智能建议时,执行简单的路径补全。读者可以将我以下的配置拷贝到 $PROFILE
,也就是上面的那个文件。
function Use-AcceptSuggestionOrComplete {
$currentCommand = $PSReadLine
# 尝试接受建议
[Microsoft.PowerShell.PSConsoleReadLine]::AcceptSuggestion()
# 检查命令行是否发生了变化
Start-Sleep -Milliseconds 10 # 给系统一点时间来更新命令行内容
$newCommand = $PSReadLine
if ($newCommand -eq $currentCommand) {
# 如果命令行没有变化,执行补全
[Microsoft.PowerShell.PSConsoleReadLine]::Complete()
}
}
# 设置 Tab 键调用自定义函数
Set-PSReadLineKeyHandler -Key Shift+Tab -Function Complete
Set-PSReadLineKeyHandler -Key Tab -ScriptBlock { Use-AcceptSuggestionOrComplete }