如何更改PowerShell提示符以仅显示父目录和当前目录?
我想缩短我的PowerShell提示符,以便它只显示父目录和当前目录。例如,如果pwd是如何更改PowerShell提示符以仅显示父目录和当前目录?,powershell,command-prompt,Powershell,Command Prompt,我想缩短我的PowerShell提示符,以便它只显示父目录和当前目录。例如,如果pwd是 C:\Users\ndunn\OneDrive\Documents\Webucator\ClassFiles\python-basics\Demos 我希望提示是: PS ..\python-basics\Demos> 我可以通过更改配置文件中的prompt()函数将其设置为PS..\Demos>: 通过在PowerShell中运行$Profile查找配置文件的位置 打开(或创建并打开)配置文件
C:\Users\ndunn\OneDrive\Documents\Webucator\ClassFiles\python-basics\Demos
我希望提示是:
PS ..\python-basics\Demos>
我可以通过更改配置文件中的prompt()
函数将其设置为PS..\Demos>
:
$Profile
查找配置文件的位置prompt()
函数:我尝试使用
split()
和负索引,但无法使其工作
而且,我只想在pwd至少下降两级时这样做。如果pwd类似于C:\folder\folder,我希望显示默认提示
有什么想法吗?试试这个(评论太长):
请尝试以下功能,该功能应同样适用于Windows和类Unix平台(在PowerShell Core中): 请注意,我选择了单个字符
…
()来表示路径的省略部分,因为。
可能与引用父目录相混淆
注意:非ASCII范围..
字符只有在封装脚本文件(假定为$PROFILE
文件)保存为带BOM[1]的UTF-8或UTF-16LE(“Unicode”)时才能正确识别
如果出于某种原因,这对您不起作用,请使用三个不同的句点(“…”
,而不是“…”
),不过请注意,这将导致较长的提示
[1] BOM表仅在Windows PowerShell中是必需的;相比之下,PowerShell Core默认采用UTF-8,因此不需要BOM。这些其他回复涉及的内容更多。即便如此,我的还是来了。如果大于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.
谢谢。这工作得很好,但它在一开始就包括了驱动器。另外,我发现mklement0的函数更清晰。顺便说一句:除非需要对提示字符串着色,否则您只需输出新的提示字符串(使其成为函数的“返回值”)-无需
写入主机
。对于PowerShell 7,请使用$PSHOME
查找存储Microsoft.PowerShell\u profile.ps1文件的位置。对我来说,这是C:\ProgramFiles\PowerShell\7
。有关详细信息,请参阅。
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 " "
}
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
}
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.