Check for last instance of a process to end

Unfortunately I can’t recall where I found this script so i am unable to give credit where it is due. If anyone stumbles upon the author please let me know so i can add appropriate credit.

Issue

Occasionally there are scenarios where actions need to be performed after the last process for and application has ended.

Traditionally with no third party tooling there are a few options in no particular order

  1. For in-house applications build in your own functionality to execute actions on the last process thread ending
  2. Create a “wrapper” script (similar to a Shim) where a script launches the application then waits for it to close
  3. Add any necessary actions to log off (the most commonly used option)

However tooling such as AppSense Environment Manager and RES allow actions/tasks to be appended to Process Stopped events.

While in most cases this is exactly what we are looking for, what about the scenario where we want to perform specific actions only when the last process thread for an application has ended?

 

Solution

The following script will scan user processes for instances of a specified application, in this below example chrome.exe.

Please note while the below was created for AppSense Environment Manager 8.4 it can be used for any method of your choice.

Change the variable highlighted (strExe) to the necessary process name.

Examples:

Process Name Line in script
chrome.exe StrExe = “chrome.exe”
firefox.exe StrExe = “firefox.exe”

Script

strComputer = "."
Set wshShell = WScript.CreateObject( "WScript.Shell" )
strUserName = wshShell.ExpandEnvironmentStrings( "%USERNAME%" )
StrExe = "chrome.exe"
StrFound = 0
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colProcessList = objWMIService.ExecQuery("Select * from Win32_Process")

For Each objProcess in colProcessList
    colProperties = objProcess.GetOwner(strNameOfUser,strUserDomain)
 If ObjProcess.Name = StrExe Then 
  If StrNameofUser = StrUserName Then
      StrFound = 1 
  End If
 End If
Next

 If StrFound = 1 Then
  Wscript.Sleep 2000
  Wscript.Quit(1)
 Else
  Wscript.Quit(0)

 End If
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s