Search code examples
windowspowershellwindows-terminal

Powershell configuration file


So I have this PowerShell configuration file, git branches are showing just fine, the problem is when I'm in every folder location is shows PS at the end:

powershell

Here's my script (I don't really know if I'm missing something here, maybe with the else path):

function prompt {
  $p = Split-Path -leaf -path (Get-Location)
  $user = $env:UserName
  $host.UI.RawUI.WindowTitle = "\" + $p + ">"
  $host.UI.RawUI.ForegroundColor = "Blue"

  if (Test-Path .git) {
    $p = Split-Path -leaf -path (Get-Location)
    git branch | ForEach-Object {
      if ($_ -match "^\*(.*)") {
        $branch = $matches[1] + " - "
        Write-Host -NoNewLine $user -ForegroundColor Magenta
        Write-Host -NoNewLine "@\"
        Write-Host -NoNewLine $p -ForegroundColor Yellow
        Write-Host -NoNewLine " - " -ForegroundColor DarkGreen
        Write-Host -NoNewLine $branch -ForegroundColor DarkGreen
      }
    }
  }
  else {
    Write-Host -NoNewLine $user -ForegroundColor Magenta
    Write-Host -NoNewLine "@\"
    Write-Host -NoNewLine $p -ForegroundColor Yellow
    Write-Host -NoNewLine " "
  }
}

Solution

  • Because your custom prompt function produces no (non-empty) success-stream output (see about_Redirection), PowerShell infers that you haven't defined this function at all, and prints its default prompt string, PS> (in your case after what the Write-Host calls printed).

    • This requirement is also explained in the conceptual about_Prompts topic.

    To avoid this problem, send at least a one-character string to the success output stream (rather than using Write-Host, which by default prints straight to the host).

    E.g. (see the penultimate line):

    function prompt {
      $p = Split-Path -leaf -path (Get-Location)
      $user = $env:UserName
      $host.UI.RawUI.WindowTitle = "\" + $p + ">"
      $host.UI.RawUI.ForegroundColor = "Blue"
    
      if (Test-Path .git) {
        $p = Split-Path -leaf -path (Get-Location)
        git branch | ForEach-Object {
          if ($_ -match "^\*(.*)") {
            $branch = $matches[1] + " - "
            Write-Host -NoNewLine $user -ForegroundColor Magenta
            Write-Host -NoNewLine "@\"
            Write-Host -NoNewLine $p -ForegroundColor Yellow
            Write-Host -NoNewLine " - " -ForegroundColor DarkGreen
            Write-Host -NoNewLine $branch -ForegroundColor DarkGreen
          }
        }
      }
      else {
        Write-Host -NoNewLine $user -ForegroundColor Magenta
        Write-Host -NoNewLine "@\"
        Write-Host -NoNewLine $p -ForegroundColor Yellow
      }
      '> ' # !! Output to the success output stream to prevent default prompt.
    }