14 out of 34 rated this helpful - Rate this topic

Exec Method (Windows Script Host)

Runs an application in a child command-shell, providing access to the StdIn/StdOut/StdErr streams.


                      object.Exec(strCommand)
object

WshShell object.

strCommand

String value indicating the command line used to run the script. The command line should appear exactly as it would if you typed it at the command prompt.

The Exec method returns a WshScriptExec object, which provides status and error information about a script run with Exec along with access to the StdIn, StdOut, and StdErr channels. The Exec method allows the execution of command line applications only. The Exec method cannot be used to run remote scripts. Do not confuse the Exec method with the Execute method (of the WshRemote object).

The following example demonstrates the basics of the Exec method.

Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")

Set oExec = WshShell.Exec("calc")

Do While oExec.Status = 0
     WScript.Sleep 100
Loop

WScript.Echo oExec.Status
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("calc");

while (oExec.Status == 0)
{
     WScript.Sleep(100);
}

WScript.Echo(oExec.Status);

Applies To:

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Is there a way to execute few releted commands in one DOS window?
I want write a script to automate some manual process:
user enters in DOS screen  few DOS commands like:
i:
cd funds
dir

I noticed each that each time I am executing wshShell.Run or wshShell.Exec commands a new DOS window is opened.
Is there a way to execute all commands in one DOS window?

Thanks

ZB
Console IO
To get console IO for the program being executed, you'll need a function like the following:

function ConsumeStdIO(e) {
    if (!e.StdOut.AtEndOfStream) {
        WScript.StdOut.Write(e.StdOut.ReadAll());
    }
    WScript.StdErr.Write(e.StdErr.ReadAll());
}
I use it like this:
var cmd = new ActiveXObject("WScript.Shell");
myApp = cmd.Exec("command");
while (myApp.Status == 0) {
    ConsumeStdIO(myApp);
    WScript.Sleep(100);
}

Executing commands provided by cmd
Some commands, such as dir and copy, are provided by cmd.exe. To execute them, you'll need to do something like the following:
copy_command = wshShell.Exec("cmd /c copy");