我试图在提示中右对齐posh-git的Write-VcsStatus部分。本质上,我的提示在左侧列出了我的主机名和当前目录,并在当前目录之后立即显示git status信息。我希望这个git状态是正确的,但是我不知道该怎么做。

这是我的提示代码:

Import-Module posh-git
function prompt {
     Update-NavigationHistory $pwd.Path
     Write-Host ([System.Net.Dns]::GetHostName() + ": ") -nonewline -foregroundcolor DarkCyan
     Write-Host (([string]$pwd).Replace("C:\Users\user", "~")) -nonewline -foregroundcolor DarkYellow
     Write-VcsStatus
     Write-Host
     Write-Host ($([char]0x2192)) -nonewline
     return " "
}

最佳答案

这是使用$Host.UI.RawUI.CursorPosition的右对齐文本的示例。

注:在Powershell_ISE中不起作用,因为它使用了非标准的控制台主机。

function Global:prompt {
     $oc = $host.ui.RawUI.ForegroundColor
     $host.UI.RawUI.ForegroundColor = "DarkCyan"
     $Host.UI.Write([System.Net.Dns]::GetHostName() + ": ")
     $host.UI.RawUI.ForegroundColor = "Yellow"
     $Host.UI.Write(([string]$pwd).Replace("C:\Users\user", "~"))
     $message = "This text is right aligned"
     $startposx = $Host.UI.RawUI.windowsize.width - $message.length
     $startposy = $Host.UI.RawUI.CursorPosition.Y
     $Host.UI.RawUI.CursorPosition = New-Object System.Management.Automation.Host.Coordinates $startposx,$startposy
     $host.UI.RawUI.ForegroundColor = "DarkGreen"
     $Host.UI.Write($message)
     $host.UI.RawUI.ForegroundColor = $oc
     $Host.UI.Write($([char]0x2192))
     return " "
 }

07-24 18:24
查看更多