powershell增加自动补全、提示建议及GIT补全

发布于 3 个月前·
2 人看过

问题描述

Windows下的原生powershell没有自动补全的功能,用着很不舒服,故此提供一个根据历史输入补全,以及git tab自动补全的功能。

解决方案

  1. 安装PowerShell、oh-my-posh和PSReadLine
    在Microsoft Store搜索PowerShell、oh-my-posh进行安装
    然后安装ReadLine
Install-Module PSReadLine
  1. 修改powershell配置,添加补全功能

首先用记事本打开powershell的配置文件,如果没有配置文件该命令会自动生成

notepad.exe $PROFILE

然后在文件中加入下列内容并保存

#Tab键会出现自动补全菜单
Set-PSReadLineKeyHandler -Key Tab -Function MenuComplete 

# 上下方向键箭头,搜索历史中进行自动补全
Set-PSReadlineKeyHandler -Key UpArrow -Function HistorySearchBackward
Set-PSReadlineKeyHandler -Key DownArrow -Function HistorySearchForward

# git的自动补全
oh-my-posh init pwsh --config "$env:POSH_THEMES_PATH/jandedobbeleer.omp.json" | Invoke-Expression
Import-Module posh-git

或者运行以下python脚本自动添加,以解决可能遇到的编码问题

import os


def generate_powershell_profile():
    # 获取 PowerShell 配置文件路径
    documents_path = os.path.expanduser("~\\Documents\\PowerShell")
    profile_path = os.path.join(documents_path, "Microsoft.PowerShell_profile.ps1")

    # 创建配置文件目录
    os.makedirs(documents_path, exist_ok=True)

    # PowerShell 配置内容
    profile_content = """
        #Tab键会出现自动补全菜单
        Set-PSReadLineKeyHandler -Key Tab -Function MenuComplete 

        # 上下方向键箭头,搜索历史中进行自动补全
        Set-PSReadlineKeyHandler -Key UpArrow -Function HistorySearchBackward
        Set-PSReadlineKeyHandler -Key DownArrow -Function HistorySearchForward

        # git的自动补全
        oh-my-posh init pwsh --config "$env:POSH_THEMES_PATH/jandedobbeleer.omp.json" | Invoke-Expression
        Import-Module posh-git 
        """

    # 使用 UTF-8 编码写入文件
    with open(profile_path, "w", encoding="utf-8") as f:
        f.write(profile_content)

    print(f"配置文件已生成:{profile_path}")
    print("请确保已安装 posh-git,可以使用以下命令安装:")
    print("Install-Module posh-git -Force -Scope CurrentUser")


if __name__ == "__main__":
    generate_powershell_profile()
  1. 主题修改(可选)
    oh-my-posh已经预装了许多的主题,可以通过修改配置的方式来修改主,可以在这个网址https://ohmyposh.dev/docs/themes, 挑选你喜欢的主题(有100多个主题),然后修改下面的配置即可
## 修改
--config "$env:POSH_THEMES_PATH/jandedobbeleer.omp.json"   
## 为你喜欢的json
## 相应的json可以在C:\Users\<UserName>\AppData\Local\Programs\oh-my-posh\themes 找到
shell
$ cd ..