Custom PowerShell prompts

Eric Schoonover picture Eric Schoonover · Aug 27, 2009 · Viewed 10.4k times · Source

I'm looking for different examples of custom Powershell prompt function implementations. If you have a custom implementation of your own please post the script. Links to existing resources are good as well.

Bonus points for posting a screenshot of what your prompt actually looks like (a preview).

Answer

stej picture stej · Aug 27, 2009

This is modified version of jaykul's prompt. The benefit is that

-there is a current history id, so you can invoke previous items from history very easily (you know the id) -it's a little reminder - I add my tasks to the prompt so I don't forget them (see the sshot)

function prompt {
  $err = !$?
  $origOfs = $ofs;
  $ofs = "|"
  $toPrompt = "$($global:__PromptVars)"
  $ofs = $origOfs;
  if ($toPrompt.Length -gt 0) { 
    Write-Host "$($toPrompt) >" -ForegroundColor Green -NoNewline }

  $host.UI.RawUI.WindowTitle = "PS1 > " + $(get-location)

  # store the current color, and change the color of the prompt text
  $script:fg = $Host.UI.RawUI.ForegroundColor
  # If there's an error, set the prompt foreground to "Red"
  if($err) { $Host.UI.RawUI.ForegroundColor = 'Red' }
  else { $Host.UI.RawUI.ForegroundColor = 'Yellow' }

  # Make sure that Windows and .Net know where we are at all times
  [Environment]::CurrentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath

  # Determine what nesting level we are at (if any)
  $Nesting = "$([char]0xB7)" * $NestedPromptLevel

  # Generate PUSHD(push-location) Stack level string
  $Stack = "+" * (Get-Location -Stack).count

  # Put the ID of the command in, so we can get/invoke-history easier
  # eg: "r 4" will re-run the command that has [4]: in the prompt
  $nextCommandId = (Get-History -count 1).Id + 1
  # Output prompt string
  # Notice: no angle brackets, makes it easy to paste my buffer to the web
  Write-Host "[${Nesting}${nextCommandId}${Stack}]:" -NoNewLine

  # Set back the color
  $Host.UI.RawUI.ForegroundColor = $script:fg

  if ($toPrompt.Length -gt 0) { 
      $host.UI.RawUI.WindowTitle = "$($toPrompt) -- " + $host.UI.RawUI.WindowTitle
  }
  " "
}
function AddTo-Prompt($str) {
  if (!$global:__PromptVars) { $global:__PromptVars = @() }
  $global:__PromptVars += $str
}
function RemoveFrom-Prompt($str) {
  if ($global:__PromptVars) {
    $global:__PromptVars = @($global:__PromptVars | ? { $_ -notlike $str })
  }
}

sshot