How can I change the PowerShell prompt to show just the parent directory and current directory?

前端 未结 3 752
梦谈多话
梦谈多话 2020-12-30 16:23

I would like to shorten my PowerShell prompt so that it just shows the parent directory and the current directory. For example, if the pwd is

C:\\Users\\ndun         


        
3条回答
  •  抹茶落季
    2020-12-30 17:15

    Try the following function, which should work on Windows and Unix-like platforms (in PowerShell Core) alike:

    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
    }
    

    Note that I've chosen single character (HORIZONTAL ELLIPSIS, U+2026) to represent the omitted part of the path, because .. could be confused with referring to the parent directory.

    Note: The non-ASCII-range character is only properly recognized if the enclosing script file - assumed to be your $PROFILE file - is either saved as UTF-8 with BOM[1] or as UTF-16LE ("Unicode").

    If, for some reason, that doesn't work for you, use three distinct periods ('...' instead of '…'), though note that that will result in a longer prompt.


    [1] The BOM is only a necessity in Windows PowerShell; by contrast, PowerShell Core assumes UTF-8 by default, so no BOM is needed.

提交回复
热议问题