Script for checking if a process is already running

Sometimes, you don't want to make an upgrade or installation if a user has already started a given process, because:

  • upgrade could fail, as the files are in use,
  • if the installer is "smart", it could kill the running process, without asking the user to save (precious) work,
  • some software (like certain browser plugins) won't install if some other software is running (i.e., a browser).

A workaround is to check if a given process is not running already. Windows XP has a "tasklist" command which can enumerate processes, but unfortunately, Windows 2000 don't.

Therefore, this script written in JScript. You can add one or more process names; it will exit with code 1 if any of these processes is running.

Example entry for packages.xml - WPKG will start upgrade of Firefox only if there is no firefox.exe process:

<upgrade cmd='cscript "%SOFTWARE%\wpkg\tools\matchprocess.js" firefox.exe' />
<upgrade cmd='"%SOFTWARE%\Internet\firefox\Firefox Setup 3.0.exe" -ms' />


The script:

// This script checks if one or more processes with a given name exist.
// If the process exists, the script exits with code 1.
// It can be used to prevent installation if a process is running and
// therefore, locks files and it's not possible or safe to upgrade it.
//
// Example usage:
// cscript matchprocess.js firefox.exe seamonkey.exe

if(WScript.Arguments.count()>0) {

        var haveMatch;

        for (i=0; i<WScript.Arguments.length; i++) {

                var curarg = WScript.Arguments(i).toLowerCase();

                var e = new Enumerator (GetObject("winmgmts:").InstancesOf("Win32_process"));

                for (; !e.atEnd(); e.moveNext()) {
                        var p = e.item ();
                        curproc = p.Name.toLowerCase();

                        if (curproc == curarg) {
                                WScript.Echo (p.Name + " exists");
                                var haveMatch = true;
                        }
                }
        }

        if (haveMatch == true) {
                WScript.Echo("Matches found");
                WScript.Quit(1);
        } else {
                WScript.Echo("No match found");
        }

} else {

        WScript.Echo ("You have to specify at least one process!");
        WScript.Quit(2);
}