Get running process info and see if a process is running

Example scripts and tips (replaces Old Scripts & Tips archive)

Moderators: Dorian (MJT support), JRL, Phil Pendlebury

Post Reply
User avatar
Marcus Tettmar
Site Admin
Posts: 7380
Joined: Thu Sep 19, 2002 3:00 pm
Location: Dorset, UK
Contact:

Get running process info and see if a process is running

Post by Marcus Tettmar » Sun Feb 06, 2005 12:23 pm

The first two of these subroutines simply display a sequence of message boxes containing info about the services and processes running on the system. The last function - IsProcessRunning - is a more compact and useful function which can be used to see if a process is running. It returns the number of running instances of the specified process name. If the specified process name does not exist/is not running it will return zero.

Code: Select all

VBSTART
'Two Subs which output data in message boxes to demonstrate how to
'get service and process information.

'displays each service and it's status
Sub Services
  strComputer = "."
  Set wbemServices = GetObject("winmgmts:\\" & strComputer)
  Set wbemObjectSet = wbemServices.InstancesOf("Win32_Service")
  For Each wbemObject In wbemObjectSet
   MsgBox "Display Name: " & wbemObject.DisplayName & vbCrLf & _
   				" State: " & wbemObject.State & vbCrLf & _
				" Start Mode: " & wbemObject.StartMode
  Next
End Sub

Sub Processes
'displays each process, it's size
'lists each process and the cpu time it has used.
	sComputer = "."
	Set oWMIService = GetObject("winmgmts:" _
    	& "{impersonationLevel=impersonate}!\\" & sComputer & "\root\cimv2")

	Set colProcessList = oWMIService.ExecQuery _
    	("Select Name, WorkingSetSize from Win32_Process")

	For Each oProcess in colProcessList
  		MsgBox oProcess.Name & "," & oProcess.WorkingSetSize / 1024
	Next

	'The current CPU percentage usage vs. other processes is not available with WMI,
	'only the total CPU time each process has used (kernelmodetime + usermodetime):

	Set oWMI = GetObject("winmgmts:")
	sWQL = "select name, kernelmodetime, usermodetime " _
    	   & " from win32_process"

	Set oResults = oWMI.ExecQuery(sWQL)

	For Each oProcess In oResults
 		MsgBox "name: " & oProcess.name & _
 		       ",kernelmodetime: " & oProcess.kernelmodetime & _
			   ",usermodetime: " & oProcess.usermodetime
	Next
End Sub
VBEND
VBRun>Services
VBRun>Processes

Code: Select all

VBSTART
'returns the number of copies of ProcessName that are running
'will return 0 if ProcessName is not running
Function IsProcessRunning(ProcessName)
	Set oWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2")
	Set colProcessList = oWMIService.ExecQuery ("Select Name from Win32_Process where Name='" & ProcessName & "'")
	IsProcessRunning = colProcessList.count
End Function
VBEND
VBEval>IsProcessRunning("opera.exe"),res
MessageModal>res

Post Reply
Sign up to our newsletter for free automation tips, tricks & discounts