如何在PowerShell中实现TXT免责声明的屏幕居中红色显示?
PowerShell实现文本垂直水平居中并红色显示的解决方案
核心实现思路
要实现免责声明的垂直+水平居中并以红色显示,需要先获取控制台的尺寸参数,计算文本块的居中位置,再逐行处理输出:
- 获取控制台的宽高尺寸
- 计算垂直方向的起始空行数,让文本块整体处于屏幕垂直中间
- 对每一行文本计算水平居中所需的左侧空格数,拼接后用
Write-Host指定红色前景色输出
修改后的完整脚本
$ConfigPath = '.\config.json' $DisclamerPath = '.\DISCLAIMER.TXT' # *** Disclaimer path *** IF (Test-Path -Path $ConfigPath -PathType Leaf) { $Content = Get-Content '.\config.json' | ConvertFrom-Json IF ($Content.Config.First) { IF (Test-Path -Path $DisclamerPath -PathType Leaf) { $DISCL = Get-Content -Path $DisclamerPath # 获取控制台尺寸 $consoleSize = $host.UI.RawUI.WindowSize # 计算垂直居中的起始空行数 $startLine = [Math]::Floor(($consoleSize.Height - $DISCL.Count) / 2) # 先输出空行到垂直起始位置 if ($startLine -gt 0) { for ($i=0; $i -lt $startLine; $i++) { Write-Host "" } } # 逐行输出居中且红色的文本 FOREACH ($LINE IN $DISCL) { # 计算水平居中的左侧空格数 $leftPadding = [Math]::Floor(($consoleSize.Width - $LINE.Length) / 2) # 确保空格数非负(避免文本过长超出控制台宽度时出错) $leftPadding = [Math]::Max($leftPadding, 0) # 输出居中红色文本 Write-Host (" " * $leftPadding + $LINE) -ForegroundColor Red } $null = Read-Host ' ' } ELSE { Write-Host 'The disclaimer file not exist.🛑' -BackgroundColor Red -ForegroundColor Black } $Content.Config.First = $false # no quotes otherwise it is interpreted as string $Content | ConvertTo-Json | Set-Content '.\config.json' -Encoding utf-8 pause } ELSE { Write-Host 'This file has already been opened for the first time !' pause } } ELSE { Write-Host 'The config file not exist.🛑' -BackgroundColor Red -ForegroundColor Black Start-Sleep -Seconds 5 RETURN }
关键代码说明
- 控制台尺寸获取:
$host.UI.RawUI.WindowSize直接读取当前控制台的宽高参数,确保适配不同的窗口大小 - 垂直居中计算:通过
($consoleSize.Height - $DISCL.Count) / 2计算需要前置的空行数,让整个文本块处于屏幕垂直中间 - 水平居中计算:对每一行文本,通过
($consoleSize.Width - $LINE.Length) / 2计算左侧需要填充的空格数,确保单行文本水平居中 - 颜色控制:通过
Write-Host的-ForegroundColor Red参数直接设置文本为红色,无需依赖第三方模块
原尝试方法失效原因
WriteColor-Core属于第三方模块(如PSScriptTools),未安装时无法调用- 直接
Write-Host仅设置了颜色,未添加居中所需的空格填充逻辑 - 自定义
centred_text函数未正确结合控制台尺寸计算居中位置
内容的提问来源于stack exchange,提问作者sylvain gagnon
相关产品推荐
相关产品推荐

