Flynn81
Flynn81

Reputation: 4178

Can CPU usage per process be determined in VBScript?

I'm looking to monitor processes running on a window 2003 server using a VBScript file. I've seen PercentProcessorTime, but that doesn't really capture usage. Is there anyway to determin a percentage usage?

Upvotes: 2

Views: 6868

Answers (1)

Jose Basilio
Jose Basilio

Reputation: 51498

It appears that it is possible using WMI in conjunction with perfmon counters. Please refer this article.

Here's the relevant code:

For Each Process in GetObject("winmgmts:").ExecQuery("Select * from Win32_Process")
     WScript.echo Process.name & " " & CPUUSage(Process.Handle) & " %"   
Next


Function CPUUSage( ProcID )
    On Error Resume Next

    Set objService = GetObject("Winmgmts:{impersonationlevel=impersonate}!\Root\Cimv2")

    For Each objInstance1 in objService.ExecQuery("Select * from Win32_PerfRawData_PerfProc_Process where IDProcess = '" & ProcID & "'")
        N1 = objInstance1.PercentProcessorTime
        D1 = objInstance1.TimeStamp_Sys100NS
        Exit For
    Next

     WScript.Sleep(2000)

    For Each perf_instance2 in objService.ExecQuery("Select * from Win32_PerfRawData_PerfProc_Process where IDProcess = '" & ProcID & "'")
        N2 = perf_instance2.PercentProcessorTime
        D2 = perf_instance2.TimeStamp_Sys100NS
        Exit For
    Next

    ' CounterType - PERF_100NSEC_TIMER_INV
    ' Formula - (1- ((N2 - N1) / (D2 - D1))) x 100
    Nd = (N2 - N1)
    Dd = (D2-D1)
    PercentProcessorTime = ( (Nd/Dd))  * 100

    CPUUSage = Round(PercentProcessorTime ,0)
End Function

Upvotes: 4

Related Questions