Monitor RAM usage remotely


  • Get RAM information
  • Define usage percentage status
  • Generate hashtable to output data
  • Final touches
  • Full Script
  • See it in action

There are several reasons why we may need to monitor the RAM usage, whether that’s a server, an endpoint or a lab, the RAM is crucial for any machine to work properly for our needs. Checking the amount of free ram in the system is a classic first step for troubleshooting sluggish issues.


  • Get RAM information

Windows Management Instrumentation (WMI) Provides a common interface and object model to access management information about operating system, devices, applications and services, I’ll not lie, many times when it comes to automating things with Powershell, is a good practice to NOT going to WMI until you’re sure that’s the better or the only choice, because usually there are other ways to do the same thing faster, still, to manage hardware and system information I think WMI it’s a good choice.

So our first step is to store the informations of the WMI class called Win32_OperatingSystem into a variable.

#Alias:
#gwmi = Get-WmiObject

$ram = gwmi -class win32_OperatingSystem

Now if you enter the variable $ram you’ll only see 6 properties:

To see all the properties of this class you need to use | select -property * where “*” is a wildcard, and means all properties in this case.

But since we are about to menage memory here, let’s be more practical by tracking only the properties that has the word “memory” in it’s name

$ram | select -property "*memory*"

Now you can see that we got two interesting properties, FreePhysicalMemory and TotalVisibleMemory, we only need these two properties to monitor the RAM usage.

To get the percentage of the amount of free ram, we divide TotalVisibleMemory with FreePhysicalMemory and then multiple the result by 100 (“quick maffs“), the tricky part is that we’ll use the .NET framework static method [math]::round to round the result, then store it in another variable called $RamFreePercentage.

$RamFreePercentage = [math]::Round(($ram.FreePhysicalMemory / $ram.TotalVisibleMemorySize) * 100)

Define usage percentage status

Well, now it’s a personal thing, you can determine what you think it’s ‘OK’, ‘Warning’ or ‘Critical’, or maybe you want even more detailed status, whatever.

So let’s say that above 50% of free ram is ‘OK’, greater or equal 25% is ‘Warning’ and below 25% is ‘Critical’.

#-gt = Greater than
#-ge = Greater or equal
#-lt = less than

if($RamFreePercentage -gt 45) {
$Status = "OK"
$Color = 'Green'
}
elseif($RamFreePercentage -ge 25) {
$Status = "Warning"
$Color = 'Yellow'
}
elseif($RamFreePercentage -lt 25) {
$Status = "Critical"
$Color ='Red'
}

  • Generate hashtable to output data

Using hashtables is a great option to output data for this purpose due to it’s customizable ability.

To do that we’ll use the syntax:

@{'Name' = "KeyName" ; 'Expression' = {value}}

We already have the $FreeRamPercentage value set up, now it’s time to set the values of free ram and total ram in GigaByte.

#Divide TotalVisibleMemorySize value for '1mb' to convert it into GigaByte, define it to [int] type to specify it as an integer number.
[int]$TotalRamGB = $Ram.TotalVisibleMemorySize / 1mb

#Divide FreePhysicalMemory value for 1mb,2 to convert it into GigaByte, define it to [float] type to specify it as a fractional value
#That ',2' in '1mb,2' is to specify 2 decimal houses.
[float]$FreeRamGB = [math]::Round($ram.FreePhysicalMemory / 1mb,2)

Now we have all the ingredients to build our hashtable output!

$Ram | Select @{ Name = 'Computer' ; Expression = {(hostname)}},
@{ Name = 'Total Ram(GB)' ; Expression = {$TotalRamGB}},
@{ Name = 'Free Ram(GB)' ; Expression = {$FreeRamGB}},
@{ Name = 'Free Ram (%)' ; Expression = {"$($RamFreePercentage)%"}},
@{ Name = 'Status' ; Expression = {$Status}}

  • Final touches

Before proceeding to the full script, we still need to do some final touches:

  • Put it into a function.
  • Add a Invoke-Command to be able to run the script remotely.
  • Add a try catch block, then if something goes wrong, like the remote host goes offline during the process you’ll be noticed.
  • Add a for loop to create a check memory cicle.

Add a start-sleep to determine the check memory interval.
I’ll only describe the function and the for loop here, because the others are not necessary since try catch it’s only a block, Invoke-Command is also only a block, and start-sleep it’s only a single line, pay attention at them in the full script though.
Function:

function Ram-Monitor {
param(
#Script will only run if the remote host responds.
[ValidateScript({Test-Connection $_ -Quiet -Count 1})]
#If the parameter -ComputerName is not specified, then the script runs in the local machine.
$ComputerName = 'localhost'
)

For Loop:

#Check memory 10 times.
for ($loop = 0; $loop -le 10; $loop++) {
#Store date in a short format (g means general) into $date variable.
$date = Get-Date -Format g
#Output the check number and date
Write-Output "`nCheck: $loop - Time: $date"
}


  • Full script


See it in action

Note that I put the check memory interval (start-sleep) to only 5 seconds for demo purposes 🙂

In the demo below, I do 3 checks in the local machine where the memory status returns ‘OK‘ and 3 checks to a remote machine where the memory status returns ‘Critical‘, check this out:

This was one more article of my Tool Making category.

I really hope this can be useful for you, and if it does, please be sure to follow me on my social hub and to share this with your mates!

Thank you very much for reading! 😉


 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.