文章

VSCode 开发,使能PowerShell Git自动完成

准备

配置 VSCode 使用 PowerShell7

VSCode快捷键打开用户配置文件(Json)ctrl+shift+p,输入open user settings,选择打开settings.json文件。添加以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
"terminal.integrated.profiles.windows": {
    "PowerShell": {
        "source": "PowerShell7",
        "icon": "terminal-powershell"
    },
    "Command Prompt": {
        "path": [
            "${env:windir}\\Sysnative\\cmd.exe",
            "${env:windir}\\System32\\cmd.exe"
        ],
        "args": [],
        "icon": "terminal-cmd"
    },
    "Git Bash": {
        "source": "Git Bash"
    },
    "PowerShell7": {
        "path": "C:\\Program Files\\PowerShell\\7\\pwsh.exe",
        "args": [],
        "icon": "terminal-powershell"
    }
},
"terminal.integrated.defaultProfile.windows": "PowerShell7",

下载 posh-git

需要使用 posh-git。 首先确定PowerShell版本(在安装PowerShell 7之后,vscode默认使用的是PowerShell 7):

1
$PSVersionTable.PSVersion

安装 posh-git

脚本执行策略必须设置为 RemoteSigned 或 Unlimited,需要以管理员身份在powershell中执行以下语句

1
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Confirm

然后安装posh-git模块:

1
2
3
4
5
6
Install-Module PowershellGet -Force
# A completely new installation
PowerShellGet\Install-Module posh-git -Scope CurrentUser -Force

# Update posh-git
PowerShellGet\Update-Module posh-git

配置 posh-git

powershell终端对$PROFILE文件进行编辑:

1
notepad $PROFILE

在文件末尾添加以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Import-Module posh-git

# 如下为可选项的配置
##To enable posh-git to be available in just the current host, execute:
Add-PoshGitToProfile

##To enable posh-git to be available in all your PowerShell hosts-console, ISE, etc, execute:
Add-PoshGitToProfile -AllHosts

# 如下 AllUsers 选项命令会出错,不使能了
##To enable posh-git to be available for all users on the system, execute:
# Add-PoshGitToProfile -AllUsers -AllHosts

##To enable posh-git to be available for all users but only for the current host
# Add-PoshGitToProfile -AllUsers

保存并关闭文件。

新开一个PowerShell,如果出现如下信息,说吗posh-git安装成功:

1
2
3
4
5
6
WARNING: Skipping add of posh-git import to file 'C:\Users\DELL\Documents\PowerShell\Microsoft.PowerShell_profile.ps1'.
WARNING: posh-git appears to already be imported in one of your profile scripts.
WARNING: If you want to force the add, use the -Force parameter.
WARNING: Skipping add of posh-git import to file 'C:\Users\DELL\Documents\PowerShell\profile.ps1'.
WARNING: posh-git appears to already be imported in one of your profile scripts.
WARNING: If you want to force the add, use the -Force parameter.

PowerShell 的一个小技巧

PowerShell按TAB键自动提示。 在powershell的$PROFILE文件中,追加以下内容:

1
2
# Shows navigable menu of all options when hitting Tab
Set-PSReadlineKeyHandler -Key Tab -Function MenuComplete

参考

本文由作者按照 CC BY 4.0 进行授权