章节 ▾ 第二版

A1.8 附录A: 其他环境中的Git - 在PowerShell中使用Git

在PowerShell中使用Git

Windows上传统的命令行终端(cmd.exe)无法真正提供定制化的Git体验,但如果你使用PowerShell,那你就很幸运了。这同样适用于你在Linux或macOS上运行PowerShell Core的情况。一个名为posh-git的包(https://github.com/dahlbyk/posh-git)提供了强大的Tab补全功能,以及一个增强的提示符,帮助你随时了解你的仓库状态。它看起来像这样

PowerShell with Posh-git
图187. 带有Posh-git的PowerShell

安装

先决条件(仅限Windows)

在你的机器上运行PowerShell脚本之前,你需要将本地的ExecutionPolicy设置为RemoteSigned(基本上是除了UndefinedRestricted之外的任何值)。如果你选择AllSigned而不是RemoteSigned,那么本地脚本(你自己的)也需要进行数字签名才能执行。而对于RemoteSigned,只有ZoneIdentifier设置为Internet(从网上下载的)的脚本才需要签名,其他的则不需要。如果你是管理员并想为该机器上的所有用户设置,请使用-Scope LocalMachine。如果你是普通用户,没有管理权限,你可以使用-Scope CurrentUser仅为你设置。

要为所有用户将ExecutionPolicy的值设置为RemoteSigned,请使用以下命令

> Set-ExecutionPolicy -Scope LocalMachine -ExecutionPolicy RemoteSigned -Force

如果你至少有PowerShell 5或安装了PackageManagement的PowerShell 4,你可以使用包管理器为你安装posh-git。

> Install-Module posh-git -Scope CurrentUser -Force
> Install-Module posh-git -Scope CurrentUser -AllowPrerelease -Force # Newer beta version with PowerShell Core support

如果你想为所有用户安装 posh-git,请改用 -Scope AllUsers 并从提升的 PowerShell 控制台执行命令。如果第二个命令失败并出现类似 Module 'PowerShellGet' was not installed by using Install-Module 的错误,你需要首先运行另一个命令

> Install-Module PowerShellGet -Force -SkipPublisherCheck

然后你可以返回并再次尝试。发生这种情况是因为随 Windows PowerShell 附带的模块是用不同的发布证书签名的。

更新PowerShell提示符

要将Git信息包含在你的提示符中,需要导入posh-git模块。要使posh-git在每次PowerShell启动时都导入,请执行Add-PoshGitToProfile命令,该命令会将导入语句添加到你的$profile脚本中。此脚本在每次打开新的PowerShell控制台时都会执行。请记住,有多个$profile脚本。例如,一个用于控制台,另一个用于ISE。

> Import-Module posh-git
> Add-PoshGitToProfile -AllHosts

从源代码安装

只需从https://github.com/dahlbyk/posh-git/releases下载posh-git版本并解压。然后使用posh-git.psd1文件的完整路径导入模块

> Import-Module <path-to-uncompress-folder>\src\posh-git.psd1
> Add-PoshGitToProfile -AllHosts

这会将正确的行添加到您的 profile.ps1 文件中,并且 posh-git 将在您下次打开 PowerShell 时激活。

有关提示符中显示的 Git 状态摘要信息的描述,请参阅:https://github.com/dahlbyk/posh-git/blob/master/README.md#git-status-summary-information。有关如何自定义 posh-git 提示符的更多详细信息,请参阅:https://github.com/dahlbyk/posh-git/blob/master/README.md#customization-variables