Search code examples
javascriptactivexjscript

Invoking an exe from Javascript with Arguments


I'm trying to invoke cmd.exe from JavaScript with arguments. But it is opening cmd.exe and doing nothing.

Below is the script.

function f_InvokeEXE() {
        var oShell = new ActiveXObject("WScript.shell");
        var commandtoRun = '"C:\\Windows\\system32\\cmd.exe"';
        var argumentString = '"C:\\Program Files (x86)\\PICT\\pict.exe" "C:\\Program Files (x86)\\PICT\\Sample.txt" > "C:\\Program Files (x86)\\PICT\\pab.xls"';
        var a = oShell.run(commandtoRun + ' ' + argumentString, 1, true);
    }

Its working fine when manually doing that. (opening command prompt and entering that command).


Solution

  • Use the /c arg for cmd.exe. Without that, it will NOT execute your command string:

    C:\Users\marc>cmd echo foo
    Microsoft Windows [Version 6.1.7601]
    Copyright (c) 2009 Microsoft Corporation.  All rights reserved.
    
    C:\Users\marc>exit
    
    C:\Users\marc>cmd /c echo foo
    foo
    
    C:\Users\marc>
    

    Note how the version WITHOUT /c just starts up a NEW shell.