We are continuing our series that answers common questions, or questions that have been asked about/of PowerShell. Todays topic: Query Windows Device for Memory Statistics. What we intend to provide is one of the many, many ways you can accomplish these same tasks within PowerShell.
All of the solutions are ours and demonstrate the author’s skill and ability level at the time of writing. That is to say, we might not always write the best PowerShell code, however, if you know of a better way we welcome that input.
Let’s start. The question is:
I need to find the total amount of system ram, how much is free, and how much is used.
The Answer:
This is absolutely possible. Again we are going to use Get-CimInstance
, but instead of output to the console directly we are going to put the object into a variable so we can manipulate that variable later. Let me explain.
$RAM = Get-CimInstance -Query "SELECT TotalVisibleMemorySize, FreePhysicalMemory FROM Win32_OperatingSystem"
What is happening above is we take a newly created variable, in this case a most obvious variable name $RAM
. Inside $RAM
we house the output of the following command to query Total Memory
and Free Memory
from the device. We need this built for later as we use this data to filter out what we want to review. Below is the output from the command. The first thing you will notice is there is no actual data visible. You are correct. Let’s get to work resolving this.
To start resolving this we will create a new variable and filter out some of the data from the $RAM
variable. To do that we use [math]::Round
which tells PowerShell that we are asking it to, one, do math
. Two, round the data
in the following brackets. We then take the $RAM
variable and Dot(.
) source
it for the TotalVisibleMemorySize
, and do it all down to the 1MB
size. Here is how that looks.
$totalRAM = [math]::Round($RAM.TotalVisibleMemorySize/1MB, 2)
Now that we have our total $RAM
we need to calculate how much $RAM
is “free”, or available to use. So in the same way that we found the TotalVisibleMemorySize
we are using FreePhysicalMemory
. The rest of the command is exactly the same. In cases like this, I copy the previous command and paste it into making my changes.
$freeRAM = [math]::Round($RAM.FreePhysicalMemory/1MB, 2)
Lastly, we want to make a variable for $usedRam
. To do this it is almost exactly the same as the previous two commands. The difference is, we are going to do one more step of math while we are in the “do math” [math]::Round
and by “do math” we are going to subtract the total $RAM
number from the $freeRAM
number giving us our $usedRAM
number we need.
$usedRAM = [math]::Round(($RAM.TotalVisibleMemorySize - $RAM.FreePhysicalMemory)/1MB, 2)
Putting it all together: