Search code examples
cmdactivexjscriptwshhta

How to get CMD output in HTA file within JavaScript


I run some CMD commands in my HTA file like

<script>
var WShell = new ActiveXObject('WScript.Shell');
WShell.run('cmd /c the_first_command');

WShell.run('cmd /c the_second_command');
</script>

and the first command may need a time to be fully executed, for example a few seconds

I need to run the next command only after the CMD output says that the previous task is fully completed.

As I understand, after the first command I can run an interval for example

var timer = setInterval(function() {

    var cmd_output_of_the_first_command = ???;

    if(~cmd_output_of_the_first_command.indexOf('A text about the task is completed')) {
        clearInterval(timer);

        WShell.run('cmd /c the_second_command');
    }

}, 500);

So the question is how to get the CMD output?


Solution

  • Ok, I've found the answer:

    var WShell = new ActiveXObject('WScript.Shell');
    var WShellExec = WShell.Exec('cmd /c the_first_command');
    
    var WShellResult = WShellExec.StdOut.ReadAll();
    if(~WShellResult.indexOf('A text about the task is completed')) {
        WShell.Run('cmd /c the_second_command');
    }
    

    No need in any interval

    OR

    just execute CMD synchronously one by one without the need to check CMD output

    WShell.Run('cmd /c the_first_command', 0, true);
    WShell.Run('cmd /c the_second_command', 0, true);