PowerShell Script to Check Memory Usage Easily
Get-CimInstance -ClassName Win32_OperatingSystem | Select-Object TotalVisibleMemorySize,FreePhysicalMemory to get total and free memory, then calculate used memory in PowerShell.Examples
How to Think About It
Algorithm
Code
$mem = Get-CimInstance -ClassName Win32_OperatingSystem $total = $mem.TotalVisibleMemorySize $free = $mem.FreePhysicalMemory $used = $total - $free Write-Output "Total Memory: $total KB" Write-Output "Free Memory: $free KB" Write-Output "Used Memory: $used KB"
Dry Run
Let's trace the script on a system with 16,777,216 KB total memory and 8,388,608 KB free memory.
Get total memory
TotalVisibleMemorySize = 16777216 KB
Get free memory
FreePhysicalMemory = 8388608 KB
Calculate used memory
Used Memory = 16777216 - 8388608 = 8388608 KB
| Total Memory (KB) | Free Memory (KB) | Used Memory (KB) |
|---|---|---|
| 16777216 | 8388608 | 8388608 |
Why This Works
Step 1: Get memory info
The Get-CimInstance command fetches system memory details from the Win32_OperatingSystem class.
Step 2: Calculate used memory
Subtracting FreePhysicalMemory from TotalVisibleMemorySize gives the amount of memory currently in use.
Step 3: Display results
The script prints total, free, and used memory in kilobytes for easy understanding.
Alternative Approaches
$mem = Get-WmiObject -Class Win32_OperatingSystem $total = $mem.TotalVisibleMemorySize $free = $mem.FreePhysicalMemory $used = $total - $free Write-Output "Total Memory: $total KB" Write-Output "Free Memory: $free KB" Write-Output "Used Memory: $used KB"
$free = (Get-Counter '\Memory\Available Bytes').CounterSamples.CookedValue $total = (Get-CimInstance -ClassName Win32_ComputerSystem).TotalPhysicalMemory $used = $total - $free Write-Output "Total Memory: $([math]::Round($total / 1KB)) KB" Write-Output "Free Memory: $([math]::Round($free / 1KB)) KB" Write-Output "Used Memory: $([math]::Round($used / 1KB)) KB"
Complexity: O(1) time, O(1) space
Time Complexity
The script runs a fixed number of system queries and calculations, so it executes in constant time.
Space Complexity
It uses a few variables to store memory values, so space usage is constant.
Which Approach is Fastest?
Using Get-CimInstance is faster and more modern than Get-WmiObject. Performance counters add complexity but provide more detailed info.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Get-CimInstance | O(1) | O(1) | Simple and modern memory check |
| Get-WmiObject | O(1) | O(1) | Legacy systems or older scripts |
| Performance Counters | O(1) | O(1) | Detailed memory stats in bytes |
Get-CimInstance instead of deprecated cmdlets for better performance and compatibility.