javascriptwindowscmdactivexactivexobject

Get Windows CMD output using ActiveX


I want to get the output of the CMD prompt in windows using ActiveX control.

When i use the following code:

var w = new ActiveXObject("WScript.Shell");  
var ex =w.Exec('cmd /c dir /b');
var ret = ex.StdOut.ReadAll();
alert(ret);

The command cmd /c dir /b works fine and I get a list of files in the alert message.

But when I use a command like cmd /c java -version I get an empty message. I tried many variations of the above command but none seems to work.

Anyone with a clue?


Solution

  • java -version returns its output at the StdErr stream, so either do:

    var ret = ex.StdErr.ReadAll();
    

    or do:

    var ex = w.Exec('cmd /C java -version 2>&1');
    

    The 2>&1 part redirects the StdErr stream (2) to StdOut (1). See this for more information.