![]() |
Table of Contents |
![]() |
Command-Line ScriptsMost of the time, you'll likely use WScript.exe to execute your scripts, and when I refer to WSH I'll generally do so as a nickname for WScript. However, WSH consists of one other executable, Cscript.exe, which is used to execute scripts on a command line. The difference with Cscript is that it doesn't provide any non-graphical means of collecting user input. In other words, although you can use a Cscript script to display command-line output, you can't use it to get input from the command-line window. Try this and you'll see what I mean:
You should see something like Figure 2.5: a basic command-line prompt, with "Displaying Output" shown in the command line. That's the work of WScript.Echo: When executed by WScript.exe, Echo creates a dialog box. When executed by Cscript.exe, Echo outputs to the command line. This allows you to create scripts that can be run graphically or from a command line. Scripts written with this technique will appear to be natively written for each environment. Figure 2.5. Executing Sample1.vbs with Cscript.exeNow try the same thing with Sample2.vbs. At first, you'll notice a command line like the one in Figure 2.6, simply displaying the output of WScript.Echo as in the previous example. However, when Cscript hits the InputBox function, it switches into graphical mode, as shown in Figure 2.7, just like WScript did. Finally, the MsgBox command also forces Cscript to display a dialog box, as shown in Figure 2.8 and exactly as WScript did-only WScript.Echo is dual mode, working differently in WScript or Cscript. Everything else defaults to a graphical mode of operation. Figure 2.6. Command-line output of WScript.echoFigure 2.7. Switching to GUI mode for InputBoxFigure 2.8. MsgBox is also GUI-onlyWhy should you care about the differences? Someday, you may want to write scripts that can be scheduled for background execution using Task Scheduler or some other tool. It's always a good idea to have scripts display some kind of output so that you can see what they're doing while you debug them. If you use Wscript.Echo for that output, and run your scripts with WScript, you'll see each output message and have to click OK to have the script continue. When you go to schedule the script for background execution, you can use Cscript instead. Your output will still display (even though you won't see it), and the script won't wait for someone to click OK. Had you used MsgBox, Cscript would throw up a dialog box, and your script would stop running until someone clicked OK. Because the script would be running in the background as a scheduled task, nobody would ever be able to click OK, and the script would "hang" forever or until you killed Task Scheduler. |
![]() |
Table of Contents |
![]() |