1. 简介

Windows 系统一个令人诟病的地方在于,它的 Shell 终端太拉胯了。且不说原先的 CMD,难用且难看,就连新加入的 PowerShell 也是一如既往的难看。 对于长期使用惯了 Zsh 的用户来说,切换到 Windows 10 系统上的 CMD 和 PowerShell 简直就是噩梦!

不过 PowerShell 一直在发展更新,目前最新版是 PowerShell 7(Windows 10 自带的是版本 5.1)。而且它也出了跨平台版本,使用也和 Linux Shell 有很多兼容。只要将 PowerShell 合理配置一下,就能达到非常好用的效果。

个人推荐 Windows Terminal + PowerShell + oh-my-posh + posh-git。

2. 安装

2.1 Windows Terminal

Windows Terminal(WT)总算是微软拿得出手的一款开源终端应用了,其可以在 MicroSoft Store 里免费下载到。WT 可以用于 CMD、PowerShell 和 WSL 等终端解释器,WT 的开源仓库:https://github.com/microsoft/terminal

2.2 PowerShell 7

Windows 10 自带的 PowerShell 太旧了,缺少很多功能。最新版本的 PowerShell 可以到其开源仓库中下载:https://github.com/PowerShell/PowerShell

2.3 oh-my-posh & posh-git

有了 WT + PowerShell 后,我们还需要针对 PowerShell 的插件框架,类似于 Zsh 的 oh-my-zsh 插件框架。oh-my-posh 为 PowerShell 提供了各种美化主题,而 posh-git 则为 PowerShell 则为 PowerShell 提供了 Git 状态显示和命令补全等功能。

遗憾的是,oh-my-posh 的作者团队已经放弃 oh-my-posh 对 PowerShell 的支持……(oh-my-posh 不应当首先支持 PowerShell 再去考虑其它 Shell 吗,我不理解……

安装好 PowerShell 7 后,Win + R 打开输入 wt 启动 Windows Terminal,然后「右键上边栏」->「设置」->「启动」->「默认配置文件」,设置为 PowerShell 7,即设置 WT 默认启用的是 PowerShell 7 。然后在 WT 中新建打开 PowerShell 7,安装 oh-my-posh 和 posh-git 模块:

1
2
Install-Module posh-git -Scope CurrentUser # posh-git
Install-Module oh-my-posh -Scope CurrentUser -RequiredVersion 2.0.496 # oh-my-posh

参考 hez2010の编程日常 博主的说明:oh-my-posh 建议用 2.x 版本,2.x 版本是 PowerShell 写的,但是 3.0 开始该插件换成用 Golang 实现了,不仅体积大了十几 mb,样式还变得更难看,速度也更慢了。

3. 配置 PowerShell

编辑 PowerShell 的配置文件 $Profile

1
notepad.exe $Profile

然后添加以下内容到配置文件中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Import-Module posh-git                                                  # 引入 posh-git
Import-Module oh-my-posh # 引入 oh-my-posh

Set-Theme Paradox # 设置主题为 Paradox

Set-PSReadLineOption -PredictionSource History # 设置预测文本来源为历史记录
Set-PSReadlineKeyHandler -Key Tab -Function Complete # 设置 Tab 键补全
Set-PSReadLineKeyHandler -Key "Ctrl+d" -Function MenuComplete # 设置 Ctrl+d 为菜单补全和 Intellisense
Set-PSReadLineKeyHandler -Key "Ctrl+z" -Function Undo # 设置 Ctrl+z 为撤销
Set-PSReadLineKeyHandler -Key "Ctrl+a" -Function BeginningOfLine # 设置 Ctrl+a 为光标到行首

Set-PSReadLineKeyHandler -Key UpArrow -ScriptBlock {
[Microsoft.PowerShell.PSConsoleReadLine]::HistorySearchBackward() # 设置向上键为后向搜索历史记录
[Microsoft.PowerShell.PSConsoleReadLine]::EndOfLine() # 设置后向搜索历史记录时光标在行尾
}
Set-PSReadLineKeyHandler -Key DownArrow -ScriptBlock {
[Microsoft.PowerShell.PSConsoleReadLine]::HistorySearchForward() # 设置向下键为前向搜索历史纪录
[Microsoft.PowerShell.PSConsoleReadLine]::EndOfLine() # 设置前向搜索历史记录时光标在行尾
}

4. 配置字体

按装上述步骤配置完在 WT 打开 PowerShell 后看起来仍然很丑,主要是字体和主题图标不兼容的问题。因此需要安装一些适合终端的字体,比如 Cascadia PL。或者到 NerdFonts 上选择一款自己喜欢的字体,下载下来解压右键为安装即可。

安装完字体后,然后「右键上边栏」->「设置」->「PowerShell 7」->「外观」->「字体」,修改为你想用的字体即可。

附录