自訂殼層環境

PowerShell 設定檔是在 PowerShell 啟動時執行的指令碼。 您可以使用設定檔來自定義環境。 您可以:

  • 新增別名、函式和變數
  • 載入模組
  • 建立 PowerShell 磁碟驅動器
  • 執行任意命令
  • 和 變更喜好設定

將這些設定放在配置檔中,可確保每當您在系統上啟動PowerShell時,都可以使用這些設定。

注意

若要在 Windows 中執行文稿,PowerShell 執行原則必須至少設定為 RemoteSigned 。 執行原則不適用於 macOS 和 Linux。 如需詳細資訊,請參閱 about_Execution_Policy

$PROFILE變數

自動 $PROFILE 變數會儲存目前會話中可用的PowerShell配置檔路徑。

有四種可能配置檔可支援不同的用戶範圍和不同的PowerShell主機。 每個配置檔文本的完整路徑會儲存在的下列成員屬性 $PROFILE中。

  • AllUsersAllHosts
  • AllUsersCurrentHost
  • CurrentUserAllHosts
  • CurrentUserCurrentHost

您可以建立配置檔文本,針對所有使用者或只有一個使用者 CurrentUser 執行。 CurrentUser 設定檔會儲存在使用者的主目錄中。

也有針對所有 PowerShell 主機或特定主機執行的配置檔。 每個 PowerShell 主機的配置檔腳本都有該主機的唯一名稱。 例如,Windows 上標準控制台主機的檔案名,或其他平臺上的預設終端機應用程式檔名為 Microsoft.PowerShell_profile.ps1。 針對 Visual Studio Code (VS Code),檔名為 Microsoft.VSCode_profile.ps1

如需詳細資訊,請參閱 about_Profiles

根據預設,參考 $PROFILE 變數會傳回「目前使用者、目前主機」配置檔的路徑。 其他配置檔路徑可以透過變數的屬性 $PROFILE 來存取。 例如:

PS> $PROFILE
C:\Users\user1\Documents\PowerShell\Microsoft.PowerShell_profile.ps1
PS> $PROFILE.AllUsersAllHosts
C:\Program Files\PowerShell\7\profile.ps1

如何建立您的個人配置檔

當您第一次在系統上安裝PowerShell時,配置檔腳本檔案及其所屬的目錄不存在。 下列命令會在不存在時建立「目前使用者、目前目前主機」配置檔腳本檔案。

if (!(Test-Path -Path $PROFILE)) {
  New-Item -ItemType File -Path $PROFILE -Force
}

Cmdlet 的 New-Item Force 參數會在不存在時建立必要的資料夾。 建立文稿檔案之後,您可以使用您慣用的編輯器來自定義殼層環境。

將自訂專案新增至您的配置檔

先前的文章討論如何使用 Tab 鍵自動完成命令預測器和別名。 這些文章顯示用來載入必要模組、建立自定義完成項、定義索引鍵系結和其他設定的命令。 這些是您想要在每個 PowerShell 互動式工作階段中可用的自訂類型。 配置檔文稿是這些設定的位置。

編輯配置檔文本最簡單的方式是在您慣用的程式代碼編輯器中開啟檔案。 例如,下列命令會在 VS Code開啟設定檔。

code $PROFILE

您也可以在 Windows、 vi Linux 或任何其他文字編輯器上使用 notepad.exe

下列配置檔文本針對先前文章中提及的許多自定義專案提供範例。 您可以在自己的設定檔中使用上述任何設定。

## Map PSDrives to other registry hives
if (!(Test-Path HKCR:)) {
    $null = New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT
    $null = New-PSDrive -Name HKU -PSProvider Registry -Root HKEY_USERS
}

## Customize the prompt
function prompt {
    $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = [Security.Principal.WindowsPrincipal] $identity
    $adminRole = [Security.Principal.WindowsBuiltInRole]::Administrator

    $prefix = $(if (Test-Path variable:/PSDebugContext) { '[DBG]: ' }
                elseif ($principal.IsInRole($adminRole)) { "[ADMIN]: " }
                else { '' })
    $body = 'PS ' + $(Get-Location)
    $suffix = $(if ($NestedPromptLevel -ge 1) { '>>' }) + '> '
    $prefix + $body + $suffix
}

## Create $PSStyle if running on a version older than 7.2
## - Add other ANSI color definitions as needed

if ($PSVersionTable.PSVersion.ToString() -lt '7.2.0') {
    # define escape char since "`e" may not be supported
    $esc = [char]0x1b
    $PSStyle = [pscustomobject]@{
        Foreground = @{
            Magenta = "${esc}[35m"
            BrightYellow = "${esc}[93m"
        }
        Background = @{
            BrightBlack = "${esc}[100m"
        }
    }
}

## Set PSReadLine options and keybindings
$PSROptions = @{
    ContinuationPrompt = '  '
    Colors             = @{
        Operator         = $PSStyle.Foreground.Magenta
        Parameter        = $PSStyle.Foreground.Magenta
        Selection        = $PSStyle.Background.BrightBlack
        InLinePrediction = $PSStyle.Foreground.BrightYellow + $PSStyle.Background.BrightBlack
    }
}
Set-PSReadLineOption @PSROptions
Set-PSReadLineKeyHandler -Chord 'Ctrl+f' -Function ForwardWord
Set-PSReadLineKeyHandler -Chord 'Enter' -Function ValidateAndAcceptLine

## Add argument completer for the dotnet CLI tool
$scriptblock = {
    param($wordToComplete, $commandAst, $cursorPosition)
    dotnet complete --position $cursorPosition $commandAst.ToString() |
        ForEach-Object {
            [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
        }
}
Register-ArgumentCompleter -Native -CommandName dotnet -ScriptBlock $scriptblock

設定檔文稿提供下列自訂的範例:

  • 為其他根登錄區新增兩個新的 PSDrive
  • 建立自定義的提示,如果您在提高許可權的會話中執行,就會變更。
  • 設定 PSReadLine 並新增keybinding。 色彩設定會使用 $PSStyle 功能來定義 ANSI 色彩設定。
  • 新增 dotnet CLI 工具的索引標籤完成。 此工具提供參數來協助解析命令行自變數。 Register-ArgumentCompleter腳本區塊會使用該功能來提供索引標籤完成。