Search code examples
processvbscriptkill-process

simple vbs process query


I am new to vbs but have done programming in c, c++ n java. I tried searching over the internet but I still cant find where am i wrong . I am making a script to kill a process named rundll if it exceeds 20% cpu usage.

Option Explicit
DIM MyPID(5), objProcess, objItems, objitem
DIM XX, I
XX = -1
dim objService
set objService = getobject("winmgmts:")
dim Process
for each Process in objService.InstancesOf("Win32_process")
if Process.Name = "rundll32.exe" Then XX = XX + 1
if Process.Name = "rundll32.exe" Then MyPID(XX) = Process.processid
Next

For I = 0 To 5
Set objProcess = GetObject("winmgmts:{impersonationLevel=impersonate}//localhost")
Set objItems = objProcess.ExecQuery("Select PercentProcessorTime from Win32_PerfFormattedData_PerfProc_Process where IDProcess=" &MyPID(I)& "")
if (IsNull(objItems)) Then
    Wscript.Echo "No process found"
    Exit For
End if
for each objItem in objItems
    if objItems = Null Then
    Wscript.Echo "No process found"
    elseif objItem>20 Then Wscript.Echo "Criminal process found :" & MyPID(I) & " = " & objItem.PercentProcessorTime
    End if
NEXT

NEXT

If the script doesnt find the process it should print no process found ,instead of a complicated null alert that i am getting now

Any help would be appreciated and so wud be suggestions


Solution

  • Instead of enumerating PercentProcessorTime for particular PIDs try enumerating processes that exceed the threshold and terminate them if their name matches the criteria:

    Set wmi = GetObject("winmgmts://./root/cimv2")
    
    perfQuery = "SELECT * FROM Win32_PerfFormattedData_PerfProc_Process " & _
                "WHERE PercentProcessorTime >= 20"
    For Each p In wmi.ExecQuery(perfQuery)
      pidQuery = "SELECT * FROM Win32_Process WHERE ProcessId = " & p.IDProcess
      For Each p1 In wmi.ExecQuery(pidQuery)
        If p1.Name = "rundll32.exe" Then p1.Terminate
      Next
    Next