Tuesday, April 17, 2012

WshShell Object

Wscript
|
WshShell

You create a WshShell object whenever you want to run a program locally, manipulate the contents of the registry, create a shortcut, or access a system folder. The WshShell object provides the Environment collection. This collection allows you to handle environmental variables (such as WINDIR, PATH, or PROMPT). 

Exec Method (Windows Script Host)

Runs an application in a child command-shell, providing access to the StdIn/StdOut/StdErr streams.
Syntax:
  object.Exec(strCommand)
 
Unlike Run method,  .Exec returns an object which returns additional information about the process started. 
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).

Example:
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
 
 
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());
}
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");
 
Status Property (WshScriptExec) 
 
Provides status information about a script run with the Exec() method.
 
Object.Status
Object
WshScriptExec object.
 The Status property is used when a program is run asynchronously.

The Status property returns a value from an enumerated type.
WshRunning ( = 0)
The job is still running.
WshFinished ( = 1)
The job has completed.
 The following code runs calc.exe and echoes the final status to the screen. 
 
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
 

 






No comments: