共用方式為


自訂殼層環境

PowerShell 配置檔是 PowerShell 啟動時執行的腳本。 您可以使用個人資料來自訂環境。 您可以:

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

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

備註

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

$PROFILE變數

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

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

  • AllUsersAllHosts
  • AllUsersCurrentHost
  • CurrentUserAllHosts
  • CurrentUserCurrentHost

您可以建立配置檔案腳本,這些腳本可針對所有使用者或僅針對單個使用者 CurrentUser 執行。 CurrentUser 設定檔會儲存在使用者的主目錄路徑下。 位置會根據作系統和您使用的PowerShell版本而有所不同。

根據預設,參考 $PROFILE 變數會傳回「目前使用者、目前主機」配置檔的路徑。 其他配置檔路徑可以透過變數的屬性 $PROFILE 來存取。 下列命令顯示 Windows 上的預設設定檔位置。

PS> $PROFILE | Select-Object *
AllUsersAllHosts       : C:\Program Files\PowerShell\7\profile.ps1
AllUsersCurrentHost    : C:\Program Files\PowerShell\7\Microsoft.PowerShell_profile.ps1
CurrentUserAllHosts    : C:\Users\username\Documents\PowerShell\profile.ps1
CurrentUserCurrentHost : C:\Users\username\Documents\PowerShell\Microsoft.PowerShell_profile.ps1
Length                 : 69

下列命令顯示Ubuntu Linux上的預設配置檔位置。

$PROFILE | Select-Object *

AllUsersAllHosts       : /opt/microsoft/powershell/7/profile.ps1
AllUsersCurrentHost    : /opt/microsoft/powershell/7/Microsoft.PowerShell_profile.ps1
CurrentUserAllHosts    : /home/username/.config/powershell/profile.ps1
CurrentUserCurrentHost : /home/username/.config/powershell/Microsoft.PowerShell_profile.ps1
Length                 : 67

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

如需詳細資訊,請參閱 about_Profiles

如何建立您的個人檔案

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

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

Cmdlet 的 New-ItemForce 參數會在不存在時建立必要的資料夾。 建立腳本檔案之後,您可以使用您慣用的編輯器來編輯您的殼層環境。

將自訂化選項新增至您的個人資料

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

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

code $PROFILE

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

下列設定檔腳本提供了在先前文章中提到的許多自訂設定的範例。 您可以在自己的個人資料中使用任何這些設定。

## 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]: ' } else { '' }
    if ($principal.IsInRole($adminRole)) {
        $prefix = "[ADMIN]:$prefix"
    }
    $body = 'PS ' + $PWD.path
    $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 並新增按鍵系結。 色彩設定會使用 $PSStyle 功能來定義 ANSI 色彩設定。
  • 新增 dotnet CLI 工具的按鍵補全功能。 此工具提供參數來協助解析命令行自變數。 Register-ArgumentCompleter 的腳本區塊會使用該功能來提供索引標籤完成。