【问题标题】:Powershell configuration filePowershell 配置文件
【发布时间】:2021-06-22 20:26:42
【问题描述】:

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

【问题讨论】:

    标签: windows powershell windows-terminal


    【解决方案1】:

    因为您的自定义 prompt 函数不会产生(非空)success-stream 输出(请参阅 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.
    }
    

    【讨论】:

    • 哦,完全忘记了默认值,非常感谢您的解释!
    • 很高兴听到它有帮助,@crisleo94;我的荣幸。坦率地说,PowerShell 应该将其行为基于prompt 函数的存在
    猜你喜欢
    • 2011-02-28
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 2012-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多