0 Replies Latest reply on Mar 4, 2015 4:55 AM by adean

    Check for last instance of a process to end

    adean Rookie
      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.

      Source: https://configmonkey.wordpress.com/2015/02/05/check-for-last-instance-of-a-process-to-end/

      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

      For in-house applications build in your own functionality to execute actions on the last process thread ending
      Create a “wrapper” script (similar to a Shim) where a script launches the application then waits for it to close
      Add any necessary actions to log off (the most commonly used option)
      However tooling such as AppSense Environment Manager and 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 and has not been tested in any other version (yet)

      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