PowerShell中Write-Host命令Tab制表符失效问题求助
解决PowerShell中Write-Host制表符对齐失效的问题
你的问题根源在于依赖控制台默认制表位(\t)对齐表格不可靠——控制台制表位是固定间隔(默认8个字符),当行内前序内容长度不一致时,制表符的跳转位置会混乱,导致部分行无法正确对齐;若变量值为空或长度较短,制表符的实际表现还会退化为普通空格。
解决方案:用格式化字符串固定列宽
放弃制表符,改用PowerShell的-f格式化运算符定义每一列的固定宽度,确保无论内容长度如何,列都能精准对齐。以下是修改后的代码:
# 自定义列宽度,可根据数据长度调整 $colWidth = 10 # 输出标题行 $title = " Categories | {0,-$colWidth} {1,-$colWidth} | % Used if Migrated" -f $oldValues.cluster, $newValues.cluster Write-Host "`r`n`r`n$title" -ForegroundColor Yellow Write-Host "---------------------------------------------------------------------------" -ForegroundColor Yellow # 总内存行 $totalMEMLine = " Total MEM (GB) | {0,-$colWidth} {1,-$colWidth} | %" -f $oldValues.TotalMEM, $newValues.TotalMEM Write-Host $totalMEMLine # 使用内存行(带颜色判断) $usedMEMPercent = ($oldValues.UsedMEM + $newValues.UsedMEM) / $newValues.TotalMEM * 100 $usedMEMColor = if ($usedMEMPercent -lt 95) { 'Green' } else { 'Red' } $usedMEMLine = " Used MEM (GB) | {0,-$colWidth} {1,-$colWidth} | {2:N1}%" -f $oldValues.UsedMEM, $newValues.UsedMEM, $usedMEMPercent Write-Host $usedMEMLine -ForegroundColor $usedMEMColor # 总CPU行 $totalCPULine = " Total CPU (GH) | {0,-$colWidth} {1,-$colWidth} | " -f $oldValues.TotalCPU, $newValues.TotalCPU Write-Host $totalCPULine # 使用CPU行(带颜色判断) $usedCPUPercent = ($oldValues.UsedCPU + $newValues.UsedCPU) / $newValues.TotalCPU * 100 $usedCPUColor = if ($usedCPUPercent -lt 95) { 'Green' } else { 'Red' } $usedCPULine = " Used CPU (GH) | {0,-$colWidth} {1,-$colWidth} | {2:N1}%" -f $oldValues.UsedCPU, $newValues.UsedCPU, $usedCPUPercent Write-Host $usedCPULine -ForegroundColor $usedCPUColor # 总存储行 $totalStorageLine = "Total Storage (GB) | {0,-$colWidth} {1,-$colWidth} | " -f $oldValues.TotalStorage, $newValues.TotalStorage Write-Host $totalStorageLine # 使用存储行(带颜色判断) $usedStoragePercent = ($oldValues.UsedStorage + $newValues.UsedStorage) / $newValues.TotalStorage * 100 $usedStorageColor = if ($usedStoragePercent -lt 95) { 'Green' } else { 'Red' } $usedStorageLine = " Used Storage (GB) | {0,-$colWidth} {1,-$colWidth} | {2:N1}%" -f $oldValues.UsedStorage, $newValues.UsedStorage, $usedStoragePercent Write-Host $usedStorageLine -ForegroundColor $usedStorageColor
关键说明:
{0,-$colWidth}:-表示左对齐,$colWidth是自定义列宽(示例设为10),确保每个列占用固定字符数,对齐效果稳定。- 拆分了颜色判断逻辑,避免行内嵌套过长导致的语法混乱,同时新增百分比显示让输出信息更完整(不需要可删除对应部分)。
内容的提问来源于stack exchange,提问作者Bob Johnson
相关产品推荐
相关产品推荐

