0

I have tried the below command to get the memory usage of the computer but getting error as infinite or 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

The expected output is -

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

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

but the output i'm getting -

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

Does anyone know how to rectify this?

Srishti
  • 13
  • 3
  • 2
    `$Totalsizemem=(gwmi Win32_PhysicalMemory | Measure-Object -Property capacity -Sum).Sum/1GB`; you can do `$Totalsizemem=[math]::Round((gwmi Win32_PhysicalMemory | Measure-Object -Property capacity -Sum).Sum/1GB,2)` if you want… – JosefZ Jun 13 '20 at 06:35

1 Answers1

1

You keep rounding and formatting the intermediate results, sacrificing accuracy to the point where your data is meaningless.

Keep it simple:

$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
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • i tried what you suggested but getting the memory usage column as blank. Name MemoryUsage(%) ---- -------------- powershell_ise.exe explorer.exe explorer.exe explorer.exe svchost.exe – Srishti Jun 17 '20 at 11:49
  • @Srishti That's odd. Did you change anything? If so, please try and execute the code as-is – Mathias R. Jessen Jun 17 '20 at 11:51
  • i tried - $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 – Srishti Jun 17 '20 at 13:04