The VBScript Network and Systems Administrator's Cafe

Apr 25 2008   1:26AM GMT

Reporting CPU usage by saving it to a file with the VBScript filesystem object

Jerry Lees Jerry Lees Profile: Jerry Lees

Last time, in my entry entitled VBScript to check CPU and Processor performance counter statistics using WMI, I asked you to modify the code I gave to include the access method type in the function. If you haven’t read the article, take a second to go back and look it over and digest the code because this article is identical to that one, except some added features.

Again I got a rather quick response to the extra credit item that I placed at the end if the article. Basically, you just need to change the code in three places to accomplish this task. We could then use this code in our previous example to create a CSV file for trending and graphing of CPU usage on a server! Here is an example of the code to do this task.

I encourage you to play around with the various methods of file access both with an existing file and a new file that doesn’t exist.

Below is a working example of the code:

Option Explicit
On Error Goto 0
Dim strSrv, strQuery,Errors
Dim Counter, Timeframe, Delay

Delay = 1000 ’1000 Milliseconds to a second
Timeframe = 300 ‘seconds (5 minutes)


strSrv = “.”
For Counter = 1 To Timeframe
 Errors = WriteTextFile (“c:\cpu-usagelog.csv”, GetFormattedCPU (strSrv), ForAppending)
 WScript.Sleep Delay
NextConst ForReading = 1, ForWriting = 2, ForAppending = 8Function GetFormattedCPU(strSrv)
    Dim objWMIService, Item, Proc, start
   
    start = Now()
  
    strQuery = “select * from Win32_PerfFormattedData_PerfOS_Processor”
    Set objWMIService = GetObject(“winmgmts:\\” & StrSrv & “\root\cimv2″)
    Set Item = objWMIService.ExecQuery(strQuery,,48)
    WScript.Echo strQuery
    For Each Proc In Item
       GetFormattedCPU = GetFormattedCPU & Proc.PercentProcessorTime & “, ”
       wscript.echo “Processor ” & Proc.Name & ” = ” & Proc.PercentProcessorTime
    Next
   
    GetFormattedCPU = GetFormattedCPU & start  
 
End Function
Function WriteTextFile (OutputFile, Data, AccessType)
    Dim wrtlog, fso
 
    On Error Resume Next
    Set fso = CreateObject(“Scripting.FileSystemObject”)
    Set wrtlog = fso.OpenTextFile (OutputFile, AccessType, true)
 If Err.Number <> 0 Then
  Set wrtlog = fso.OpenTextFile (OutputFile, ForWriting, true)
 End If
    wrtlog.WriteLine(Data)
    WriteTextFile = Err.Number ‘You can use Err.Description here to debug.
    On Error Goto 0
End Function
You now have all the pieces for a fully functional performance logging script, so you’re well on your way to being able to troubleshoot problems deep in the night without getting up and turning on Perfmon. The creates a comma separated value file called cpu-usagelog.csv at the root of the C: drive while the output looks similar to the last time, except it is repeated and I put a time/date stamp in the code by using a new command, now().Also, pay attention to the error handling around the line that writes the data to the file, you’ll likely not see an error related to the file not existing and you using the append access methods, because I’ve checked for it while opening a file. Lastly, notice the for next loop around the function call to call it Timeframe times (Timeframe is multiplied time the sleep Delay to get how long it will capture data). Also notice another new command: Wscript.Sleep, which basically pauses the execution for the number of milliseconds you specify in Delay.

As always, this code works perfectly. However, sometimes the formatting of the blog breaks the code if you copy and paste it into your editor. So, if you’d like to not type or troubleshoot any syntax errors due to the copy and paste problems– I’ve provided the code for download, plus example output files  from my final tests for you. You’ll find the code and other files available for download from my website’s (www.websystemsadministration.com) File Depot under the ITKE Blog Scripts category. Enjoy and happy scripting!

Extra credit: Try and modify this script to monitor something else that is useful to you. Let us all know how you’ve used it.

2  Comments on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
  • Leathal
    I tried this code and Microsoft reports it the ' in line six is a invalid character, so I removed all the ' and text after them from the code and attempted to run it again this game the "." in the strSrv line is now invalid. Any ideas why? A.
    0 pointsBadges:
    report
  • Jerry Lees
    Yes, Thank you for asking this question. Unfortunately, the blogging software does some funky stuff to a ' and a " to make it "pretty"... which of course causes stuff to break all over the place in code. This is why at the end of every article I place a link to a section of my website, http://www.websystemsadministration.com, where I always place the example code I used to create the article for download. If you go there you will find the code for every blog entry I make here available for download. Plus, I generally place files in the zip files that show the output I received when the script ran-- cleaned of confidential information, if there was any in the output, of course. If you have further problems, don't hesitate to post again, I'll be happy to help further.
    5,335 pointsBadges:
    report

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: