电源外壳配置文件

Powershell configuration file

所以我有这个 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 " "
  }
}

因为您的自定义 prompt 函数不产生(非空)success-stream 输出(参见about_Redirection), PowerShell 推断您根本没有定义此函数,并打印其 default 提示字符串,PS> (在你的情况下 afterWrite-Host 调用的打印内容)。

  • 此要求也在概念性 about_Prompts 主题中进行了解释。

为了避免这个问题,发送至少一个一个字符的字符串到成功输出流(而不是使用Write-Host, 默认情况下直接打印到 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.
}