【问题标题】:How can I change the PowerShell prompt to show just the parent directory and current directory?如何更改 PowerShell 提示符以仅显示父目录和当前目录?
【发布时间】:2019-10-26 20:18:43
【问题描述】:

我想缩短我的 PowerShell 提示符,以便它只显示父目录和当前目录。例如,如果密码是

C:\Users\ndunn\OneDrive\Documents\Webucator\ClassFiles\python-basics\Demos

我希望提示是:

PS ..\python-basics\Demos> 

我可以通过更改 Profile 文件中的 prompt() 函数使其成为 PS ..\Demos>

  1. 通过在 PowerShell 中运行 $profile 来查找配置文件的位置。
  2. 打开(或创建并打开)配置文件。
  3. 更改(或添加)以下prompt() 函数:

function prompt
{
  $folder = "$( ( get-item $pwd ).Name )"
  "PS ..\$folder> "
}

我尝试使用 split() 和负索引,但无法正常工作。

另外,我只想在 pwd 至少下降两级时执行此操作。如果 pwd 类似于 C:\folder\folder,我想显示默认提示。

有什么想法吗?

【问题讨论】:

标签: powershell command-prompt


【解决方案1】:

这些其他回复涉及更多。即便如此,这是我的。如果大于 30 个字符,我们会缩短路径。完成。

Function Prompt {
    If ("$($executionContext.SessionState.Path.CurrentLocation)>".Length -le 30) {
        "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) ";
    } Else {
        "PS ...\$(Split-Path -Path $executionContext.SessionState.Path.CurrentLocation -Leaf)$('>' * ($nestedPromptLevel + 1)) ";
    } # End If.
} # End Function: Prompt.

【讨论】:

    【解决方案2】:

    尝试以下函数,它应该可以在 Windows 和类 Unix 平台(在 PowerShell Core 中)同样工作:

    function global:prompt {
      $dirSep = [IO.Path]::DirectorySeparatorChar
      $pathComponents = $PWD.Path.Split($dirSep)
      $displayPath = if ($pathComponents.Count -le 3) {
        $PWD.Path
      } else {
        '…{0}{1}' -f $dirSep, ($pathComponents[-2,-1] -join $dirSep)
      }
      "PS {0}$('>' * ($nestedPromptLevel + 1)) " -f $displayPath
    }
    

    请注意,我选择了单个字符 (HORIZONTAL ELLIPSIS, U+2026) 来表示路径中省略的部分,因为 .. 可能会与引用 父目录 目录混淆。

    注意:非 ASCII 范围的 字符只有在封闭的脚本文件(假定为您的 $PROFILE 文件)被保存为 UTF-8 时才能正确识别带有 BOM [1] 或 UTF-16LE(“Unicode”)。

    如果由于某种原因这对您不起作用,请使用三个不同的句点('...' 而不是 '…'),但请注意,这会导致更长的提示。


    [1] BOM 只是 Windows PowerShell 中的必需品;相比之下,PowerShell Core 默认采用 UTF-8,因此不需要 BOM。

    【讨论】:

      【解决方案3】:

      试试这个(评论太长了):

      function prompt 
      {
          $aux=$executionContext.SessionState.Path.CurrentFileSystemLocation.Path -Split '\\|\/'
          if ( $aux.Count -le 3 ) {
              Write-Host ("PS $($aux -join '\')>") -NoNewline # -ForegroundColor Cyan
          } else {
              Write-Host ("PS $($aux[0])\..\$($aux[-2..-1] -join '\')>") -NoNewline # -ForegroundColor Cyan
          }
          return " "
      }
      

      【讨论】:

      • 谢谢。这工作得很好,但它在一开始就包括驱动器。另外,我发现 mklement0 的功能更清晰。
      • 顺便说一句:除非需要着色提示字符串,否则您可以简单地输出新的提示字符串(使其成为函数的“返回值") - 不需要Write-Host
      猜你喜欢
      • 1970-01-01
      • 2016-01-06
      • 2016-11-23
      • 2010-12-22
      • 2014-07-26
      • 1970-01-01
      • 1970-01-01
      • 2010-11-13
      • 2014-01-21
      相关资源
      最近更新 更多