Skip to content

PowerShell prompt function customization

The prompt function in PowerShell determines the text displayed at the command line, and customizing it allows for enhanced visual feedback and integration with terminal features.^[400-devops-02-os-and-linux-basics-windows.md]

Integration with Windows Terminal

Custom prompts can trigger specific behaviors in modern terminal emulators like Windows Terminal. By using escape codes, the prompt function can communicate the current working directory path to the terminal host^[400-devops-02-os-and-linux-basics-windows.md]. This facilitates features such as opening a new tab or pane in the same directory as the current session^[400-devops-02-os-and-linux-basics-windows.md].

Implementation Examples

Basic Profile Prompt

A simple customization involves creating a prompt function in the PowerShell profile (e.g., C:\Program Files\PowerShell\7\Profile.ps1) that overrides the default output^[400-devops-02-os-and-linux-basics-windows.md]. The following example constructs a prompt string that includes the current location and appends an ANSI escape sequence (9;9) containing the path for the terminal to interpret^[400-devops-02-os-and-linux-basics-windows.md].

function prompt {
  $loc = $($executionContext.SessionState.Path.CurrentLocation);
  $out = "PS $loc$('>' * ($nestedPromptLevel + 1)) ";
  $out += "$([char]27)]9;9;`"$loc`"$([char]27)\"
  return $out
}

Git-Aware Prompt

More advanced implementations can integrate version control status. The snippet below demonstrates using a GitPromptScriptBlock to include Git status information in the prompt line^[400-devops-02-os-and-linux-basics-windows.md]. It also uses the ANSI escape sequence 9;12 alongside the directory path sequence^[400-devops-02-os-and-linux-basics-windows.md].

function prompt
{
  $loc = Get-Location

  $prompt = & $GitPromptScriptBlock

  $prompt += "$([char]27)]9;12$([char]7)"
  if ($loc.Provider.Name -eq "FileSystem")
  {
    $prompt += "$([char]27)]9;9;`"$($loc.Path)`"$([char]7)"
  }

  $prompt
}

Sources

  • 400-devops-02-os-and-linux-basics-windows.md