Tuesday, August 31, 2010

ECMAScript to run a command on windows

I had the need to try to run a batch script on the command line using Novell IDM.  I was able to develop a quick function in ECMAScript in order to accomplish this task.  Simply call the following function from policy and pass it the full string of what you want run on the command line and it'll return any output it may return.  Very simple, yet infinitely useful.

importPackage(Packages.java.io);
importPackage(Packages.java.util);

function runCommand(commandString)
{
        var runtime = new java.lang.Runtime.getRuntime();
        var process = runtime.exec(commandString);
        var is = process.getInputStream();
        var isr = new Packages.java.io.InputStreamReader(is);
        var br = new Packages.java.io.BufferedReader(isr);
        var line = new java.lang.String();
        var fulltext = new java.lang.String();
       
        while ((line = br.readLine()) != null )
        {
            fulltext = fulltext + line;
        }
       
        return fulltext;
}

6 comments:

  1. good post... but ...
    how can i do the same for linux??
    thanks!

    ReplyDelete
  2. Should be the same thing, just use your linx commands instead. Sorry for the delay, wasn't getting emails on comments.. thats been fixed too!

    ReplyDelete
  3. You are simply awesome

    ReplyDelete
  4. I call your function from my ECMA script executing a provisioning request and receive the error " An error 'ReferenceError: java is not defined' " !!

    ReplyDelete
    Replies
    1. Ok ! I haven't called the importPackage statement.
      But... now.. I receive the error 'ReferenceError: importPackage is not defined'

      Delete
    2. Can you post more about the specific use case, show both the ecma object and the policy that you called it from. Are you doing this from a driver or trying to do it from a workflow?

      Delete