让你的windows shell更好用,打造类fish/zsh的powershell

7,004 阅读2分钟

背景

在linux、macos使用过fish或者zsh的同学应该明白,windows中频繁输入各种重复的命令是多么繁琐的一件事。以下介绍powershell新版PSReadLine带有的预测补全功能和安装方法,并推荐其他好用的powershell模块,让你的各种命令更加得心应手。 最终预览,包含功能:

  1. 自动补全历史命令,逐字补全
  2. posh主题
  3. ZLocation目录跳转
  4. 2022-3-29新增: bash风格的Tab补全

3.gif

安装流程

下载PSReadLine

powershell版本需要大于5.1,执行如下命令查看版本信息

$PSVersionTable

如果powershell的版本大于等于6,将自动包含最新的PSReadLine,不需要再单独安装。 PSReadLine github

执行如下命令,安装PSReadLine2.1.0。

Install-Module PSReadLine -RequiredVersion 2.1.0

考虑到国内网络环境,下载时往往需要挂上代理才能下载成功

Install-Module PSReadLine -RequiredVersion 2.1.0 -Proxy http://127.0.0.1:7890

离线环境安装PSReadLine

部分同学的开发环境下载文件可能受限,如下介绍离线环境安装PSReadLine的方法

  1. 先在正常环境下下载文件
Save-Module -Name "PSReadLine" -path "D:\tmp\" -proxy http://127.0.0.1
  1. 将文件拷贝到开发环境
  2. 移动文件到指定目录
# 显示module路径
$env:PSModulePath -split ";"
# 我的电脑显示如下
# C:\Users\yuhen\Documents\WindowsPowerShell\Modules
# C:\Program Files\WindowsPowerShell\Modules
# C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules

老版本的PSReadLine存放在C:\Program Files\WindowsPowerShell\Modules目录下,将下载的文件放入对应目录下即可。

配置加载文件

下载完成后,可以先测试是否能正常使用,执行:

Import-Module PSReadLine
Set-PSReadLineOption -PredictionSource History

测试效果如下:

1.gif

不区分大小写,完美补全历史命令。

启动powershell时,自动加载对应配置

  1. 查看是否有powershell配置文件
Test-path $profile
  1. 如果显示为false,手动创建一个,如果为true,则修改对应文件
New-item –type file –force $profile
  1. 编辑配置
notepad $profile
  1. 新增如下内容
# ...
+ Import-Module PSReadLine
+ Set-PSReadLineOption -PredictionSource History

修改逐字补全快捷键

Autosuggestion除了可以使用键补全全部外,还可以使用option + →选择下一个单词,现在为powershell配置同样的功能。

修改$PROFILE如下:

Import-Module PSReadLine
Set-PSReadLineOption -PredictionSource History
+ # alt在windows中有特殊用途,这里使用ctrl键代替
+ Set-PSReadLineKeyHandler -Chord "Ctrl+RightArrow" -Function ForwardWord

现在按下ctrl + →可以逐字补全了,效果如下:

2.gif

结论

windows terminal 已经出来许久了,windows的terminal也有了好看的UI、标签页等功能,搭配上autosuggestion这样的功能,windows shell的体验将更好。

其他的好用powershell工具

新增

2022-3-29: 修改Tab补全为bash风格

Import-Module PSReadLine
Set-PSReadLineOption -PredictionSource History
# alt在windows中有特殊用途,这里使用ctrl键代替
Set-PSReadLineKeyHandler -Chord "Ctrl+RightArrow" -Function ForwardWord
# bash风格Tab补全
+ Set-PSReadlineKeyHandler -Key Tab -Function MenuComplete