20. 03. 2024 Attilio Broglio Unified Monitoring

How to Monitor the TOP N RAM-Using Processes

After developing a custom check for monitoring the most CPU demanding processes on Windows servers, we implemented a similar check for RAM usage. Like I described in that previous post, we built this command via PowerShell. PowerShell provides the cmdlet: Get-Counter that gets performance counter data directly from the performance monitoring instrumentation in the Windows family of operating systems. Filtering the result by \Process(*)\Working Set – Private, we can clean the “CookedValue” and apply some mathematical operations to obtain the percentage of RAM used by a specific process.

Here you can see a code snippet that explain the steps used for obtaining the information:

# By default check top 5 processes
if (-not $number) { $number = 5 }
$DICT = @{}
# Top 5 process Memory Usage (%)
$PROCESSES = (Get-Counter "\Process(*)\Working Set - Private" 2>$null).CounterSamples
$Mem = [math]::Ceiling($(get-wmiobject -class "Win32_ComputerSystem").TotalPhysicalMemory )
for ($i = 0; $i -lt $PROCESSES.Count; $i++) {
    if ($($PROCESSES[$i].CookedValue) -gt 0) {
        $DICT[$PROCESSES[$i].InstanceName] += $([math]::Round($PROCESSES[$i].CookedValue / $Mem * 100, 2));
    }
}
$TOPPROCESSES = ($DICT.GetEnumerator() | Sort-Object { $_.Value } -Descending) | Select-Object -Skip 1 -First $number;
Write-Output "[OK] Top $(if ($number -lt $DICT.Count) {Write-Output $number} else { Write-Output $($DICT.Count-1)}) process(es):";
foreach ($item in $TOPPROCESSES) {
    Write-Host $item.Name " " $item.Value"%";
}
Write-Host -NoNewline " | ";
for ($i = 0; $i -lt $TOPPROCESSES.Count; $i++) {
    Write-Host -NoNewline "$($TOPPROCESSES[$i].Name -replace "\s","_")=$($TOPPROCESSES[$i].Value)%;;;0; "
}

After these transformations we get the desired output:

C:\Users\pb00320\Desktop\check_top_ram_processes.ps1
[OK] Top 5 process(es):
chrome 3.39 %
msedgewebview2 2.97 %
memory compression 2.37 %
searchapp 1.62 %
code 1.32 %
 | chrome=3.39%;;;0; msedgewebview2=2.97%;;;0; memory_compression=2.37%;;;0;;
searchapp=1.62%;;;0; code=1.32%;;;0;

This script doesn’t need any additional packages, can be run as a common PowerShell script and can be easily customized.

These Solutions are Engineered by Humans

Did you find this article interesting? Does it match your skill set? Our customers often present us with problems that need customized solutions. In fact, we’re currently hiring for roles just like this and others here at Würth Phoenix.

Attilio Broglio

Attilio Broglio

Author

Attilio Broglio

Leave a Reply

Your email address will not be published. Required fields are marked *

Archive