章節 ▾ 第二版

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 檔案中,下次你開啟 PowerShell 時,posh-git 將會啟用。

有關提示符中顯示的 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

scroll-to-top