如何在Powershell提示符中右对齐某些内容?

4

我想将posh-git中的Write-VcsStatus右对齐。我的提示符左侧列出了主机名和当前目录,然后立即打印git状态信息。我希望这个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 " "
}
1个回答

0

这里是一个右对齐文本的例子,使用$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 " "
 }

你为什么在提示之前添加了“Global”标签?还有,我在哪里可以找到关于$Host这样的文档?我找不到它。我正在尝试学习PowerShell,但很难找到关于全局变量和参数的资源。 - pradyuman
如果您以管理员身份运行,则需要“全局”标记才能使其在2012(我的操作系统)上工作。不幸的是,我不知道有关PS $host的任何真正文档,尽管在此网站上有一些示例可供搜索。 - Jan Chrbolka
你如何捕获 cmdlet 的输出?例如,我有这个函数 Write-VcsStatus。我想捕获它的输出并将其放入 $message 中。我该怎么做? - pradyuman
@asuna 请阅读:Get-Help about_Automatic_Variables - user4003407
取决于函数的作用。如果它返回一个字符串,那么可能只需要 $ message = Write-VcsStaus,但如果它写入到控制台,那就会比较困难。 - Jan Chrbolka

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接