VBS Script to Detect CPU Useage
This VB Script can read the CPU Metric from a server which i think could come in very handy.
The script here is set to perform an action on any user who is consuming greater than 25% CPU, that action could be to log them off, or kill the greedy process. The script excludes system, service and ctx_* accounts from being processed.
Dim strGetServerName
Set WshShell = CreateObject("WScript.Shell")
' --------------------------------------------------------------------
' Read Parameters
' --------------------------------------------------------------------
On Error Resume Next
strArguments = WScript.Arguments.Item(0)
if strArguments = "" then
wscript.quit
Else
strGetServerName = strArguments
End if
For each Process in GetObject("Winmgmts:{impersonationLevel=impersonate}!\\" & strGetServerName & "\root\cimv2").ExecQuery("Select * from Win32_Process")
if Process.GetOWner(User) = 0 then UserID = lcase(User)
if Process.GetOwnerSID(Sid) = 0 then UserSID = Sid
if UserID <> "system" And instr(UserID,"service") = 0 And instr(UserID,"ctx_") = 0 AND UserID <> "" then
CurrProc = Process.name
CurrUsge = CPUUSage(Process.Handle)
if CurrUsge > 25 then
!!!! PerformAction here !!!!
End if
End If
Next
wscript.quit
Function CPUUSage( ProcID )
On Error Resume Next
Set objService = GetObject("Winmgmts:{impersonationLevel=impersonate}!\\" & strGetServerName & "\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(1000)
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