JScript: how to run external command and get output?

China☆狼群 提交于 2019-12-05 09:59:06
var strOutput = oExec.StdOut.ReadAll();

In Javascript it is a call to a function and MUST include the parenthesis

var oShell = WScript.CreateObject("WScript.Shell");
var ret = oShell.Run('cmd /c dir', 1 /* SW_SHOWNORMAL */, true /* bWaitOnReturn */);
WScript.Echo("ret " + ret);

That assigns the exit code of the command to the ret variable, not its standard output.

To read the command's standard output, you can use cmd /c to run the command and redirect its standard output to a file, then read the file.

You can also use the WshScriptExec object and read the StdOut property, but if you use that object you can't control the window state like you can with WshShell.Run (like above).

Here is a sample script:

function runCommand(command) {
  var fso = new ActiveXObject("Scripting.FileSystemObject");
  var wshShell = new ActiveXObject("WScript.Shell");
  do {
    var tempName = fso.BuildPath(fso.GetSpecialFolder(2), fso.GetTempName());
  } while ( fso.FileExists(tempName) );
  var cmdLine = fso.BuildPath(fso.GetSpecialFolder(1), "cmd.exe") + ' /C ' + command + ' > "' + tempName + '"';
  wshShell.Run(cmdLine, 0, true);
  var result = "";
  try {
    var ts = fso.OpenTextFile(tempName, 1, false);
    result = ts.ReadAll();
    ts.Close();
  }
  catch(err) {
  }
  if ( fso.FileExists(tempName) )
    fso.DeleteFile(tempName);
  return result;
}

var output = runCommand("dir");
WScript.Echo(output);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!