Monday, October 27, 2008

How to Retrieve CPU and Memory Utilization using a script (VBS)

Here's a simple vbs script that displays the CPU and memory utilization of a computer (works on Windows XP and above):

' Salvador Manaois III
' http://badzmanaois.blogspot.com
' =========================================================================
' You have a royalty-free right to use, modify, reproduce and distribute
' this script (and/or any modified version) in any way you find useful,
' provided that you agree that the author has no
' warranty, obligations or liability for the script. If you modify
' or quote the script, you must retain this copyright notice.
' -------------------------------------------------------------------------
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
'Get CPU Usage
myQuery = "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor WHERE Name = '_Total'"
For Each objItem in objWMIService.ExecQuery(myQuery)
   ProcTime = "Processor time " & objItem.PercentProcessorTime & "  %"
next
'Get Memory Information
myQuery = "select FreeVirtualMemory,FreePhysicalMemory from Win32_OperatingSystem"
for each objItem in objWMIService.ExecQuery(myQuery)
for each oProperty in objItem.Properties_
if oProperty.Name = "VirtualMemFreeMemory" then
VirtualMemFree = oProperty.Value
elseif oProperty.Name = "PhMemFreeMemory" then
PhMemFree = oProperty.Value
end if
next
next
myQuery = "select TotalVirtualMemory,TotalPhysicalMemory from Win32_LogicalMemoryConfiguration"
for each objItem in objWMIService.ExecQuery(myQuery)
for each oProperty in objItem.Properties_
if oProperty.Name = "TotalVirtualMemory" then
VirtualTotal = oProperty.Value
elseif oProperty.Name = "TotalPhysicalMemory" then
PhysicalTotal = oProperty.Value
end if
next
next
VirtualUsed = 100 - (100 * (VirtualMemFree / VirtualTotal))
PhysicalUsed = 100 - (100 * (PhMemFree / PhysicalTotal))
wscript.echo Date() & " " & Time()
wscript.echo "Processor Time : " & ProcTime
wscript.echo "Percent Used Virutal Memory" & VirtualUsed
wscript.echo "Percent Used Physical Memory" & PhysicalUsed

No comments: