首页 > 解决方案 > 将输出设为无限或 Nan

问题描述

我尝试了以下命令来获取计算机的内存使用情况,但得到的错误为无限或 NaN。

    $Totalsizemem=gwmi Win32_PhysicalMemory | Measure-Object -Property capacity -Sum | Foreach {" 
    {0:N2}" -f ([math]::round(($_.Sum / 1GB),2))}
    gwmi -computername localhost Win32_Process | Sort WorkingSetSize -Descending | Select 
    Name,@{n="Memoryusage(%)";Expression ={[math]::round(($_.WorkingSetSize / 1GB),1) / 
    $Totalsizemem*100}} | Select -First 10 | Format-Table -AutoSize | Out-Default

预期的输出是 -

    Name                                              Memoryusage(%)
    ----                                              --------------

    powershell_ise.exe                             0.655737704918033
    explorer.exe                                   0.655737704918033
    explorer.exe                                   0.655737704918033
    explorer.exe                                   0.655737704918033

但我得到的输出 -

    Name                 Memoryusage(%)
    ----                 --------------
    powershell_ise.exe                ∞
    svchost.exe                       ∞
    explorer.exe                    NaN
    svchost.exe                     NaN
    explorer.exe                    NaN

有谁知道如何纠正这个?

标签: powershellmemory-managementget-wmiobject

解决方案


您不断舍入和格式化中间结果,牺牲准确性到您的数据毫无意义的地步。

把事情简单化:

$Totalsizemem = Get-WmiObject Win32_PhysicalMemory | Measure-Object -Property Capacity -Sum |Select -Expand Sum
Get-WmiObject Win32_Process |Sort WorkingSetSize -Descending |Select Name,@{Name='MemoryUsage(%)';Expression={$_.WorkingSetSize * 100 / $Totalsizemem}} -First 10

推荐阅读