Howto: Start application from JScript and specify 'Start in folder' attribute

Let's say you have an application that has to be started from a specific location. In other words, if you were to launch this application and expect it work properly, you'll need to either:
1) Create a shortcut and specify 'Start in' folder or
2) Navigate to the folder where your application resides and start it from there

If you didn't have to use it in a script, you could simply run the following command from command prompt: start /D"path to your application folder" "Path to your application's .exe"
So, in a real example it would look like this:

start /D"C:\Program Files\Notepad++\" "C:\Program Files\Notepad++\Notepad++.exe"

Command above will start Notepad++ with 'Start in' parameter as "C:\Program Files\Notepad++\"

Now, let's say that you have to launch that application from within a script and you don't want your command prompt left hanging until you exit your application. In order for you to do it, you'll need to create a WScript object. The following code snippet will work for VBScript and JScript/JavaScript:

function RunWindowsCommand (commandStr, workingDir) {
   // this command is for TestComplete
   var wsShell = Sys.OleObject("WScript.Shell");
   // this command is for JScript
   // var wsShell = WScript.CreateObject("WScript.Shell");
 
  // check to see if user specified workingDir
  if (typeof(workingDir) != "undefined") {
    wsShell.CurrentDirectory = workingDir;
  }
 
  // try to run the command
  try {
    wsShell.Exec(commandStr);
  }
  catch (ex) {
    // handle your exception.
    // for TestComplete, it'll look like this:
    Log.Warning("Command '" + commandStr + "' failed to execute. " + ex.description);
  }
}

And, to run this function do one of the following...
With Working Directory set:

function MyTest1() {
  var appPath = "C:\\Program Files\\Notepad++\\";
  var appExec = "Notepad++.exe";
  RunWindowsCommand (appPath + appExec, appPath);
}

Without setting working directory:

function MyTest2() {
  var appPath = "C:\\Program Files\\Notepad++\\";
  var appExec = "Notepad++.exe";
  RunWindowsCommand (appPath + appExec);
}

Comments