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

PowerShell Export-Excel丢失小数及超80%值高亮问题求助

解决PowerShell导出Excel的小数丢失与高亮问题

问题1:小数丢失的修复

你的问题源于系统区域设置使用逗号作为小数分隔符,Export-Excel将逗号识别为千分位分隔符,导致数值被错误解析为整数。解决核心是明确指定数值列的格式,确保Excel正确识别小数:

  • 在导出时为CPU %和Memory %列设置带两位小数的数值格式。

问题2:超80%高亮的实现

利用ImportExcel模块的-ConditionalFormat参数,添加条件格式规则:当单元格值大于80时,填充红色背景。

修改后的完整脚本

$Servers = Get-Content "$env:USERPROFILE\Desktop\serversTest.txt"
$Array = @()

ForEach ($Server in $Servers) {
    $Check = $Processor = $ComputerMemory = $RoundMemory = $Object = $null
    $Server = $Server.trim()

    Try {
        # 获取CPU使用率(统一保留两位小数)
        $Processor = [math]::Round(
            (Get-WmiObject -ComputerName $Server -Class win32_processor -ErrorAction Stop | 
             Measure-Object -Property LoadPercentage -Average | Select-Object Average).Average,
            2
        )

        # 获取内存使用率(保留两位小数)
        $ComputerMemory = Get-WmiObject -ComputerName $Server -Class win32_operatingsystem -ErrorAction Stop
        $Memory = ((($ComputerMemory.TotalVisibleMemorySize - $ComputerMemory.FreePhysicalMemory)*100)/ $ComputerMemory.TotalVisibleMemorySize)
        $RoundMemory = [math]::Round($Memory, 2)
        
        # 创建自定义对象(简化语法)
        $Object = [PSCustomObject]@{
            "Server name" = $Server
            "CPU %"       = $Processor
            "Memory %"    = $RoundMemory
        }

        $Object
        $Array += $Object
    }
    Catch {
        Write-Host "No se encuentra el servidor ($Server): "$_.Exception.Message
        Continue
    }
}

# 导出并设置格式与条件高亮
If ($Array) { 
    $excelParams = @{
        Path              = "C:\users\4749\Informe.xlsx"
        AutoSize          = $true
        NumberFormat      = @{
            "CPU %"    = "0.00"
            "Memory %" = "0.00"
        }
        ConditionalFormat = @(
            @{
                Column          = "CPU %"
                RuleType        = "GreaterThan"
                Condition       = 80
                BackgroundColor = "Red"
            },
            @{
                Column          = "Memory %"
                RuleType        = "GreaterThan"
                Condition       = 80
                BackgroundColor = "Red"
            }
        )
    }
    $Array | Export-Excel @excelParams
}

关键修改说明

  1. 小数格式修复:

    • 对CPU使用率计算结果添加[math]::Round(),确保和内存使用率统一保留两位小数
    • 在Export-Excel的NumberFormat参数中指定CPU %和Memory %列使用0.00格式,强制Excel识别为带两位小数的数值
  2. 高亮效果实现:

    • 通过ConditionalFormat参数添加两条规则,分别对CPU %和Memory %列设置:当值大于80时,单元格背景设为红色
    • 使用哈希表传递导出参数,让脚本结构更清晰易维护

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 00:14:52