如何更改 PowerShell 提示符以仅显示父目录和当前目录?

2023-11-21

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

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

我希望提示是:

PS ..\python-basics\Demos> 

我可以让它变得只是PS ..\Demos>通过改变prompt()配置文件中的函数:

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

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

我尝试使用split()和负索引,但无法让它发挥作用。

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

有任何想法吗?


尝试以下函数,它应该可以在 Windows 和类 Unix 平台上运行(在 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
}

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

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").

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


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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何更改 PowerShell 提示符以仅显示父目录和当前目录? 的相关文章

随机推荐