/**
 * +----------------------------------------------------------------------------+
 * |                          Jeffrey M. Hunter                                 |
 * |                      jhunter@idevelopment.info                             |
 * |                         www.idevelopment.info                              |
 * |----------------------------------------------------------------------------|
 * |      Copyright (c) 1998-2011 Jeffrey M. Hunter. All rights reserved.       |
 * |----------------------------------------------------------------------------|
 * | FILE       : ExternalCommands.js                                           |
 * | CLASS      : Miscellaneous Functions                                       |
 * | PURPOSE    : Demonstrates how to run external commands from within a       |
 * |              script using two different methods:                           |
 * |                                                                            |
 * |                - Exec()   (WSH Version 5.6 or higher)                      |
 * |                - Run()                                                     |
 * |                                                                            |
 * |              In most cases, you will want to take advantage of the Exec()  |
 * |              method as it provides support for standard streams, which     |
 * |              makes it easy to capture output from the external commands    |
 * |              (command). Keep in mind that the Exec() method is only        |
 * |              available in WSH 5.6 or higher.                               |
 * | PARAMETERS : None                                                          |
 * | USAGE      : cscript ExternalCommands.js //NoLogo                          |
 * | NOTE       : As with any code, ensure to test this script in a development |
 * |              environment before attempting to run it in production.        |
 * +----------------------------------------------------------------------------+
 **/


// -----------------------------------------------------------------------------
//   - SET GLOBAL VARIABLES AND ANY OBJECTS
//   - CALL MAIN FUNCTION
//   - THEN CLEAN UP OBJECTS AND EXIT SCRIPT
// -----------------------------------------------------------------------------

// Global WSH Objects
var g_objShell = new ActiveXObject("WScript.Shell");

g_MAIN_RETURN = main();

g_objShell = null;
WScript.Quit(g_MAIN_RETURN);



/**
 * -----------------------------------------------------------------------------
 * runExample
 *
 * This function demonstrates how to call an external command using the
 * Run() method. There are several options to the Run() method that controls
 * how this script will make the call to the external command. In this
 * example method, we will Run the external command and wait for it to 
 * complete. Also, while the script is running, it will not pop up a new 
 * DOS window to show its output.
 *
 *     Run(strCommand, [intWindowType], [blnWaitOnReturn]);
 *
 *          strCommand      - Text string of command to run
 *          intWindowType   - How to display window:
 *                              0 = Hides the window.
 *                              1 = Displays and activates new window with
 *                                  original size and position.
 *                              2 = Activates window in minimized form.
 *                              3 = Activates window in maximized form.
 *                              4 = Displays new window (original size and
 *                                  position) but keeps active window active.
 *                              5 = Activates and displays window in current
 *                                  size and position.
 *                              6 = Minimizes specified window and activates
 *                                  the next window down (in z-order).
 *                              7 = Minimizes new window but keeps active
 *                                  window active.
 *                              8 = Displays window in current state, but keeps
 *                                  active window active.
 *                              9 = Restores a minimized window to its original
 *                                  size and position.
 *                              10 =Displays the new window based on the
 *                                  current state of the calling programs'
 *                                  window.
 *          blnWaitOnReturn - Should the script wait until command is complete?
 *                               true  = Wait
 *                               false = No wait
 *
 * Returns
 *      Integer value returned from the external command.
 * -----------------------------------------------------------------------------
 **/

function runExample() {

    var strCommand, errRetValue;

    strCommand = "%comspec% /C ping 127.0.0.1";
    errRetValue = g_objShell.Run(strCommand, 0, true);
    
    return(errRetValue);
    
}


/**
 * -----------------------------------------------------------------------------
 * runExampleCaptureOutput
 *
 * This function demonstrates how to call an external command using the
 * Run() method while capturing its output. Unlike the WSH Exec() method,
 * Run() does not support standard streams able to capture output from
 * the external command. This function provides a workaround by creating a
 * TextStream object used for reading and writing the commands output to a text
 * file.
 *
 * Returns
 *      Integer value returned from the external command.
 * -----------------------------------------------------------------------------
 **/

function runExampleCaptureOutput() {

    var strCommand, strOutput;
    var strTempEnv, strTempFileName;
    var errRetValue;

    // Get TEMP Environment variable and Temp file name
    strTempEnv = g_objShell.ExpandEnvironmentStrings("%temp%");
    strTempFileName = strTempEnv + "\\runOutput.txt";
    WScript.Echo("Writing output to TEMP file: " + strTempFileName);
    
    strCommand = "%comspec% /C ping 127.0.0.1 > " + strTempFileName;
    
    errRetValue = g_objShell.Run(strCommand, 0, true);
    
    strOutput = readOutput(strTempFileName);
    WScript.Echo(strOutput);
    
    return(errRetValue);
    
}


/**
 * -----------------------------------------------------------------------------
 * readOutput
 *
 * Utility function used to read a text file and return its output.
 *
 * Returns
 *      Text contained in the file.
 * -----------------------------------------------------------------------------
 **/

function readOutput(strFileName) {

    var objFSO = new ActiveXObject("Scripting.FileSystemObject");
    var objTextFile, strOutput;
    
    if (objFSO.FileExists(strFileName)) {
        objTextFile = objFSO.OpenTextFile(strFileName, 1, false);
        strOutput = "";
        while(!objTextFile.AtEndOfStream) {
            strOutput = strOutput + objTextFile.ReadLine() + "\n";
        }
        objTextFile.Close();
    } else {
        strOutput = "ERROR: File not found!";
    }
    
    return(strOutput);
    
}


/**
 * -----------------------------------------------------------------------------
 * execExample
 *
 * This function demonstrates how to call an external command using the
 * Exec() method while capturing its output. The Exec() method was introduced
 * in WSH 5.6. For versions of WSH prior to 5.6, you will need to use the Run()
 * method.
 *
 * The Exec() method returns a WshScriptExec object. This object provides 
 * support for standard streams (StdIn, StdOut, and StdErr), making it possible
 * to "capture" the output of the external command. 
 *
 * Returns
 *      Integer value returned from the external command.
 * -----------------------------------------------------------------------------
 **/

function execExample() {

    var strCommand, objWshScriptExec, objStdOut, strOutput;

    strCommand = "%comspec% /C ping 127.0.0.1";
    objWshScriptExec = g_objShell.Exec(strCommand);
    
    objStdOut = objWshScriptExec.StdOut;
    strOutput = "";
    while(!objStdOut.AtEndOfStream) {
        strOutput = strOutput + objStdOut.ReadLine() + "\n";
    }
    WScript.Echo(strOutput);
    
    return(0);
    
}


/**
 * -----------------------------------------------------------------------------
 * main
 *
 * Main function used to enclose the primary script logic.
 *
 * Returns
 *      Exit code from primary script logic.
 * -----------------------------------------------------------------------------
 **/

function main() {
    
    var errRetValue;
    
    
    WScript.Echo("-----------------------------------------");
    WScript.Echo("Run Example");
    WScript.Echo("-----------------------------------------");
    
    errRetValue = runExample();
    
    if (errRetValue == 0) {
        WScript.Echo("Success!\n");
    } else {
        WScript.Echo("Error! (Return value = " + errRetValue + ")\n");
    }


    WScript.Echo("-----------------------------------------");
    WScript.Echo("Run Example - (Capture Output)");
    WScript.Echo("-----------------------------------------");
    
    errRetValue = runExampleCaptureOutput();
    
    if (errRetValue == 0) {
        WScript.Echo("Success!\n");
    } else {
        WScript.Echo("Error! (Return value = " + errRetValue + ")\n");
    }    


    WScript.Echo("-----------------------------------------");
    WScript.Echo("Exec Example");
    WScript.Echo("-----------------------------------------");
    
    errRetValue = execExample();
    
    if (errRetValue == 0) {
        WScript.Echo("Success!\n");
    } else {
        WScript.Echo("Error! (Return value = " + errRetValue + ")\n");
    }    
    
    return(0);

}

