You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改磁盘空间报告脚本,使红色临界单元格文字变白?

磁盘空间报告脚本文字颜色修正方案

核心问题定位

你遇到的问题大概率是因为脚本生成的是HTML格式报告,而非控制台输出,单纯设置PowerShell的FontColor变量无效——HTML样式需要用CSS来控制文字和背景色。

具体修改步骤

情况1:脚本直接拼接HTML单元格

找到脚本中判断磁盘空间临界状态的代码块,通常是类似判断剩余百分比低于阈值的逻辑,修改单元格的内联样式:

# 原代码示例(仅设置红色背景)
if ($disk.FreePercent -lt 10) {
    $tdStyle = 'style="background-color: red;"'
}

# 修改后(同时设置白色文字)
if ($disk.FreePercent -lt 10) {
    $tdStyle = 'style="background-color: red; color: white;"'
}

然后在生成<td>标签时应用这个样式:

"<td $tdStyle>$($disk.FreePercent)%</td>"

情况2:使用ConvertTo-Html命令生成报告

如果脚本用ConvertTo-Html生成报告,需要在内嵌CSS中定义临界状态的样式类:

# 内嵌CSS样式
$css = @"
<style>
.critical {
    background-color: red;
    color: white;
}
.normal {
    background-color: white;
}
</style>
"@

# 生成HTML时给临界单元格添加类
$diskReport = Get-WmiObject Win32_LogicalDisk | ForEach-Object {
    $freePercent = [math]::Round(($_.FreeSpace / $_.Size)*100,2)
    [PSCustomObject]@{
        Drive = $_.DeviceID
        FreeSpacePercent = if ($freePercent -lt 10) { "<span class='critical'>$freePercent%</span>" } else { "$freePercent%" }
    }
}

# 拼接CSS和HTML输出
$css + ($diskReport | ConvertTo-Html) | Out-File "DiskReport.html"

情况3:控制台直接输出

如果脚本是在控制台输出结果,需要用Write-Host的参数同时指定背景和前景色:

foreach ($disk in Get-WmiObject Win32_LogicalDisk) {
    $freePercent = [math]::Round(($disk.FreeSpace / $disk.Size)*100,2)
    if ($freePercent -lt 10) {
        Write-Host "驱动器 $($disk.DeviceID) 剩余空间: $freePercent%" -BackgroundColor Red -ForegroundColor White
    } else {
        Write-Host "驱动器 $($disk.DeviceID) 剩余空间: $freePercent%"
    }
}

关键提醒

如果你的脚本有其他特殊样式逻辑(比如引用外部CSS文件),只需要在对应红色背景的样式规则里添加color: white即可,核心是确保红色背景的元素同时设置了文字颜色为白色。

内容的提问来源于stack exchange,提问作者user28823175

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 12:30:07