[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Edit this existing script to include a time frame

Posted on 2007-08-03
5
Medium Priority
?
229 Views
Last Modified: 2013-11-05
I have this existing script to monitor CPU Usage, what I would like is to keep the format as the software requires it in this way but to somehow make the check run so that alert will be generated if CPU is > 50% for more than 30 seconds


Function GetCpuUsage( strComputer, strUsername, strPassword, strCPU, numMaxCpuUsage )

On Error Resume Next

    Dim objWMIService, objSWbemLocator, objConnect, numCpuUsage

    GetCpuUsage = retvalUnknown ' Unless indicated otherwise

    if (strUsername = "") then      
            'Connect to remote host on same domain using same security context
            Set objWMIService = GetObject("winmgmts:{impersonationLevel=Impersonate}!\\" & strComputer &"\root\cimv2:Win32_Processor='" & strCPU & "'")
      else      
            'Connect to remote host using different security context and/or different domain
            Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
            Set objConnect = objSWbemLocator.ConnectServer(strComputer, "root\cimv2", strUsername, strPassword)
            objConnect.Security_.ImpersonationLevel = 3
            Set objWMIService = objConnect.Get("Win32_Processor='" & strCPU & "'")
      end if

    If( Err.Number <> 0 ) Then
        EXPLANATION = "Unable to get information about '" & strCPU & "' on computer '" & strComputerName & "'"
        GetCpuUsage = retvalUnknown
    Else
      numCpuUsage  = objWMIService.LoadPercentage
      VALUE = numCpuUsage
      If( numCpuUsage > numMaxCpuUsage ) Then
                 EXPLANATION = "CPU usage is too high; usage=[" & numCpuUsage & "%]"
                  GetCpuUsage = False
        Else
                  EXPLANATION = "CPU usage is below maximum; usage=[" & numCpuUsage & "%]"
                  GetCpuUsage = True
        End If
      
    End If  

End Function
0
Comment
Question by:coch
  • 2
  • 2
5 Comments
 
LVL 32

Accepted Solution

by:
Robberbaron (robr) earned 1500 total points
ID: 19633436
I've rewritten to use a second function as calling routine and also left the response text to be a separate item

My preference is to have a function do just 1 thing...
like GetCpuCsage just gets current usage, CheckCPU gets average

'---------------------8<-------------------------------------


Function GetCpuUsage( strComputer, strUsername, strPassword, strCPU )

    On Error Resume Next

    Dim objWMIService, objSWbemLocator, objConnect, numCpuUsage

    GetCpuUsage = -999 ' Unless indicated otherwise

    if (strUsername = "") then      
            'Connect to remote host on same domain using same security context
            Set objWMIService = GetObject("winmgmts:{impersonationLevel=Impersonate}!\\" & strComputer &"\root\cimv2:Win32_Processor='" & strCPU & "'")
      else      
            'Connect to remote host using different security context and/or different domain
            Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
            Set objConnect = objSWbemLocator.ConnectServer(strComputer, "root\cimv2", strUsername, strPassword)
            objConnect.Security_.ImpersonationLevel = 3
            Set objWMIService = objConnect.Get("Win32_Processor='" & strCPU & "'")
      end if

    If( Err.Number <> 0 ) Then
        GetCpuUsage = -999
    Else
        GetCpuUsage  = objWMIService.LoadPercentage
       
     
    End If  

End Function

Function CpuCheck ( numPeriod, numMaxCpuUsage, strComputer, strUsername, strPassword, strCPU )
    dim cputimer1,cpuval1,cputimer2,cpuval2,cputimer3, cpuval3
   
    'returns 0 if ok, -9 is error, > 0 if cpu > numMaxCPU
    'check 3 times to ensure that CPU usage is not just spikes...
   
      cputimer1=TIMER()
      cpuval1 = GetCpuUsage ( strComputer, strUsername, strPassword, strCPU )
     
      'evaluate initial data
      if cpuval1 = -9999 then CpuCheck = -9 : Exit sub
      if cpuval1 < numMaxCpuUsage then CpuCheck=0 : exit sub
     
      WScript.Sleep(numPeriod * 1000 /2 )        'sleep for xx seconds
   
      cputimer2=TIMER()
      cpuval2 = GetCpuUsage ( strComputer, strUsername, strPassword, strCPU )
      WScript.Sleep(numPeriod * 1000 /2 )        'sleep for xx seconds
     
      cputimer3=TIMER()
      cpuval3 = GetCpuUsage ( strComputer, strUsername, strPassword, strCPU )
         
      'evaluate average data
      if cpuval2 = -9999 OR cpuval3 = -9999 then CpuCheck = -9 : Exit sub
      if cpuval2 < numMaxCpuUsage OR cpuval2 < numMaxCpuUsage then CpuCheck=0 : exit sub

      CpuCheck = (cpuval1+cpuval2+cpuval3)/3     'average cpu usage
     
End Function
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 19636783
robberbaron,

I'm not familiar with the Timer function, but it looks like you are getting an average of the CPU Usage over a period of time.....and the Sleep periods would mean there is no checking during that time.

Would it be more accurate to use a DateDiff function that continually checks if 30 secconds have passed yet, and gets reset to the current time, when it falls back below that threshhold?  I know this is pretty much a manual "timer", and if the inbuilt Timer function does that anyway, that would be great.

Please provide your thoughts.  I am interested in the Timer function.

Regards,

Rob.
0
 

Author Comment

by:coch
ID: 19637023
Thanks for the response, just a couple of things, when I run the script I get an error on line 43, char 52, error Expected 'Function', code 800A03F7, Source Compilation error.
And the other thing is that the script has to follow the instructions below
functions should always return:
" -1 (True); Return -1 in case the Monitor Function is successful. For
instance, if your function checks the existence of a certain
directory, and it does exist, then return -1;
" 0 (False); Return 0 in case the Monitor Function is not successful.
For instance, if your function checks the existence of a certain
directory, and it does not exist, then return 0;
" 1 (Unknown); Return 1 in case the Monitor Function cannot
determine True or False. For instance, if your function checks the
existence of a certain directory on a server, but it cannot find the
server at all (for instance because the computer is down), return 1;

Use the following guidelines when writing a new function:
" The routine must be a Function, not a Sub;
" The Function must return True (-1), False (0) or Unknown (1);
" Optionally, use the EXPLANATION system variable to add your
own explanation to the result of the function; this EXPLANATION
is shown in the client program each time the check is made;
" All variables must be 'dimmed', except EXPLANATION.
EXPLANATION is a Monitor system variable
automatically dimmed by the Monitor service.
The function must be written according to the following template:
Const retvalUnknown = 1
Function Function_i( var1, var2, ..., varn )
If ( Not Pre-condition ) Then
EXPLANATION = "Unable to determine..."
Function_i = retvalUnknown
Else
If( condition ) Then
EXPLANATION = "Yes it is true because ..."
Function_i = True
Else
EXPLANATION = "No its not true because ..."
Function_i = False
End If
End If
End Function
where Function_i is an arbitrary name for the function.
0
 
LVL 32

Assisted Solution

by:Robberbaron (robr)
Robberbaron (robr) earned 1500 total points
ID: 19637064
1/ i dont think you want to continually check CPU usage as that is resouce intensive. But you could set time span to be 300 seconds, and change so it checks at 10th intervals.

So my option was to check 3 times in say 30 sec and if all 3 were over limit, then we can guess that the cpu load was continuous.  Rather than getting 2 spikes 30 sec apart.


2/ the Timer function simply returns the number of seconds since midnight.

3/ function templates.... ok. seems unusual but.
  Change the -9 to 1
      'evaluate average data
      if cpuval2 = -9999 OR cpuval3 = -9999 then CpuCheck = 1 : Exit sub
      if cpuval2 < numMaxCpuUsage OR cpuval2 < numMaxCpuUsage then  CpuCheck=-1 : exit sub      'no troubles with CPU usgae

      CpuCheck = (cpuval1+cpuval2+cpuval3)/3     'average cpu usage
                EXPLANATION = "CPU usage is too high; usage=[" & CpuCheck & "]"
     cpucheck=0     'usage is a problem !
EXIT FUNCTION
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 19642588
Right, yeah, not checking continuously does make sense.....good thinking....

Thanks for the info....

Rob.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Welcome back!  My apologies for taking so long to write part two of this series; it's been a long time coming!  As I promised in Part 1, this article will focus on how to locate those elusive AD properties that you are searching for.  Why is this us…
Welcome, welcome!  If you are new to the series and haven't been following along, please take a brief moment to review the first three installments: Part 1 (http://www.experts-exchange.com/Programming/Languages/Visual_Basic/VB_Script/A_266-VBScri…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…
Suggested Courses

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question