I am trying to monitor % of physical memory usage of local machine with performance counter in power shell. In resource monitor, under memory tab, we can get to know how much % of physical memory used.Also in Task manager, under Performance tab--> Memory, we can see how much % of memory used. check images for references as well.
I am following below steps in power shell to achieve same result
1) using below command , I am getting maximum physical memory
$totalPhysicalmemory = gwmi Win32_ComputerSystem | % {$_.TotalPhysicalMemory /1GB}
2) Using below counter command , I am getting average available memory
$avlbleMry = ((GET-COUNTER -Counter "\Memory\Available MBytes"|select -ExpandProperty countersamples | select -ExpandProperty cookedvalue )/1GB
3) Calculation to find % of Physical memory used: (Doing math round to 2 digits after decimal)
(($totalPhysicalmemory-$avlbleMry)/$totalPhysicalmemory)*100
Am i doing right?Is this is the correct approach to get % of memory used? Is there any better approach to get % of physical memory using WMI commands or performance counter or some other way?
I think your approach is right, but the memory units are wrong.
Also, using Get-CimInstance is recommended.
So the code look like this
# use the same unit `/1MB` and `Available MBytes`
$totalPhysicalmemory = (Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory /1MB
$avlbleMry = (Get-Counter -Counter "\Memory\Available MBytes").CounterSamples.CookedValue
(($totalPhysicalmemory-$avlbleMry)/$totalPhysicalmemory)*100
and some other ways
# Win32_OperatingSystem, KB
$osInfo = Get-CimInstance -ClassName Win32_OperatingSystem
$total = $osInfo.TotalVisibleMemorySize
$free = $osInfo.FreePhysicalMemory
$used = $total - $free
$usedPercent = $used/$total * 100
echo $usedPercent
# Microsoft.VisualBasic, bytes
Add-Type -AssemblyName Microsoft.VisualBasic
$computerInfo = [Microsoft.VisualBasic.Devices.ComputerInfo]::new()
$total = $computerInfo.TotalPhysicalMemory
$free = $computerInfo.AvailablePhysicalMemory
$used = $total - $free
$usedPercent = $used/$total * 100
echo $usedPercent