Search code examples
cmdjscripthta

How can I send several commands to the same cmd instance from HTA file?


I have launched a cmd instance using WScript.Shell in an HTA file. The cmd window is opened and ready to receive commands. How can I send commands there?

<html>
<head>
<script language="javascript">
var wsh = new ActiveXObject('WScript.Shell');
var cmd = wsh.Exec("cmd.exe");
function to_cmd(a_command){
    cmd.Exec(a_command);
}
</script>
<title>UI</title>
<hta:application id="app">
</head>
<body>
    <input type=button onclick="to_cmd('dir')">
</body>
</html>

Yes, this code contains an error(s) because I still cannot find correct methods or objects to do it the right way.

It can be any approach (not only similar to mine). The main idea is the ability to send different commands to the same cmd window by clicking on an HTML-button.

No, I do not want to send separate commands directly to the shell object.


Solution

  • You can accomplish this by writing directly to the process StdIn:

    // Create a shell
    var shell = new ActiveXObject('WScript.Shell');
    
    // Open the command prompt with /k flag to keep it open
    var cmd = shell.exec('%comspec% /k');
    
    // Method to write to the prompt's StdIn and redirect output to the console
    // NOTE: If you want a blank console screen, remove just the ">CON" text
    var runCommand = function(command) {
      cmd.StdIn.Write(command + ' >CON\n');
    };
    
    // Run a command
    runCommand('echo Hello');
    
    // Run another one after 1.5 seconds
    setTimeout(function() {
      runCommand('echo World!');
    }, 1500);