1

所以我有这个 PowerShell 配置文件,git 分支显示得很好,问题是当我在每个文件夹位置时显示PS在末尾:

电源外壳

这是我的脚本(我真的不知道我是否在这里遗漏了一些东西,也许是else路径):

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 " "
  }
}
4

1 回答 1

3

因为您的自定义prompt函数不产生(非空)成功流输出(请参阅about_Redirection),PowerShell 推断您根本没有定义此函数,并打印其默认提示字符串,PS>(在您的情况下,在调用打印之后Write-Host) .

为避免此问题,请至少向成功输出流发送一个字符字符串(而不是使用Write-Host,默认情况下直接打印到主机)。

例如(见倒数第二行):

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.
}
于 2021-03-26T01:28:30.777 回答