PowerShell 模块PSWriteColor 在单行输出多种颜色方面已经做得很好。您可以直接从 GitHub 下载它并使用 Import-Module <PATH-TO>\PSWriteColor.psd1 导入它,或者直接使用 Install-Module -Name PSWriteColor 从 PowerShell 库安装它。
语法简写为Write-Color -Text "GreenText","RedText","BlueText" -Color Green,Red,Blue。因此,我们需要在 [String[]]$Text 参数前面加上一个包含必要空格的字符串,以便使消息在屏幕上居中,并相应地在 [ConsoleColor[]]$Color 参数前面加上颜色。
这是一个用于居中的小辅助函数。
#Requires -Modules @{ ModuleName="PSWriteColor"; ModuleVersion="0.8.5" }
function WriteColor-Centered {
param(
[Parameter(Mandatory=$true)][string[]]$Text,
[Parameter(Mandatory=$true)][ConsoleColor[]]$Color
)
$messageLength = 0
$Text | ForEach-Object { $messageLength += $_.Length }
[String[]] $centeredText = "{0}" -f (' ' * (([Math]::Max(0, $Host.UI.RawUI.BufferSize.Width / 2) - [Math]::Floor($messageLength / 2))))
$centeredText += $Text
[ConsoleColor[]]$OutColor = @([ConsoleColor]::White)
$OutColor += $Color
Write-Color -Text $centeredText -Color $OutColor
# Alt.: use WriteColor-Core, see below
# WriteColor-Core -Text $centeredText -Color $OutColor
}
我从this stackoverflow answer复制了空格计算。
编辑:有人问我是否可以在不导入模块的情况下完成这项工作。老实说,我现在感觉有点脏,因为我进入了一个编写良好的模块的源代码,从中剥离了所有功能和错误处理并将其粘贴到这里。
无论如何,如果您在上面的包装函数中替换 Write-Color 的调用并调用以下 WriteColor-Core,则可以省去加载 PSWriteColor 模块。
function WriteColor-Core {
param(
[Parameter(Mandatory=$true)][string[]]$Text,
[Parameter(Mandatory=$true)][ConsoleColor[]]$Color
)
# Fallback defaults if one of the values isn't set
$LastForegroundColor = [console]::ForegroundColor
# The real deal coloring
for ($i = 0; $i -lt $Text.Count; $i++) {
$CurrentFGColor = if ($Color[$i]) { $Color[$i] } else { $LastForegroundColor }
$WriteParams = @{
NoNewLine = $true
ForegroundColor = $CurrentFGColor
}
Write-Host $Text[$i] @WriteParams
# Store last color set, in case next iteration doesn't have a set color
$LastForegroundColor = $CurrentFGColor
}
Write-Host
}