• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 249
  • Last Modified:

Edit this existing script to include a time frame

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
coch
Asked:
coch
  • 2
  • 2
2 Solutions
 
Robberbaron (robr)Commented:
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
 
RobSampsonCommented:
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
 
cochAuthor Commented:
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
 
Robberbaron (robr)Commented:
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
 
RobSampsonCommented:
Right, yeah, not checking continuously does make sense.....good thinking....

Thanks for the info....

Rob.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now