获取无限或 Nan 的输出

Getting output as infinite or 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

有谁知道如何纠正这个问题?

您不断对中间结果进行舍入和格式化,牺牲了准确性,以至于您的数据变得毫无意义。

保持简单:

$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