JScript: how to run an external command and get output?

I am running my JScript file using cscript.exe. In a script, I need to call an external console command and get the output.

I tried:

var oShell = WScript.CreateObject("WScript.Shell");
var oExec = oShell.Exec('cmd /c dir');
WScript.Echo("Status "+oExec.Status);
WScript.Echo("ProcessID "+oExec.ProcessID);
WScript.Echo("ExitCode "+oExec.ExitCode);

and

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

but no luck: the command runs (most likely) without errors, but I have no output. Note that "cmd / c dir" is just an example here to make sure I get the output at all.

So how do I do this?

Update: I tried converting this https://stackoverflow.com/a/464690/1544036/... to JScript, but with no luck:

var oShell = WScript.CreateObject("WScript.Shell");
var oExec = oShell.Exec('cmd /c dir');
var strOutput = oExec.StdOut.ReadAll;
WScript.Echo("StdOut "+strOutput);

var strOutput = oExec.StdErr.ReadAll;
WScript.Echo("StdErr "+strOutput);

Error Microsoft JScript runtime error: Object doesn't support this property or methodin linevar strOutput = oExec.StdOut.ReadAll;

+4
source share
2 answers
var strOutput = oExec.StdOut.ReadAll();

In Javascript, this is a function call and MUST include brackets

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

ret, .

, cmd/c , .

WshScriptExec StdOut, , , , WshShell.Run(, ).

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);
+4

Source: https://habr.com/ru/post/1544035/


All Articles