1. Trang chủ
  2. » Công Nghệ Thông Tin

sams teach Yourself windows Script Host in 21 Days phần 4 pdf

51 540 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 51
Dung lượng 1,72 MB

Nội dung

example, and another task that is scheduled to run Weekly. Now it’s time to discuss the reason you’re involved with the AT command: the task you want to schedule. One way to schedule these scripts is to embed them in a .bat or .cmd file and schedule the batch file with AT. The command portion of AT can exist with or without surrounding quotation marks. I prefer to include surrounding quotes to avoid any possible problems. As an example, I have slightly modified the dir.vbs script that comes with the WSH distribution. For those of you who have not yet used it, the script simply reads the contents of the C:\TEMP directory on your computer and displays the results in a series of dialog boxes (one dialog box per file found). Rather than have the script display several dialog boxes, each containing a filename, I used the wscript.echo command to display the output at the console. The modified script looks like this: Set WSHShell = WScript.CreateObject("WScript.Shell") Set objFileSystem = Wscript.CreateObject("Scripting.FileSystemObject") Set objFolder = objFileSystem.GetFolder("C:\temp") Set colFiles = objFolder.Files For Each FileObj in colFiles strFileName = FileObj.Name wscript.echo strFileName Next Using this modified script, you will create a batch file that contains the necessary command to invoke the script and log the contents to a text file. In this example, the text file is named C:\DIR.TXT. If you haven’t done so already, move the modified DIR.VBS file to the root of your C:\ drive. You can store the script file anywhere; the location I specified is used simply to make this example easier. Now you create the batch file that will run the script. Using a simple text editor, such as Notepad, create a document that contains the following command: C:\WINNT\SYSETM32\CSCRIPT.EXE C:\DIR.VBS > C:\DIR.TXT Save the document in the root of your C:\ drive, and name it DIR.BAT. Let me dissect the command that is contained in the batch file. The first part of the command, C:\WINNT\SYSTEM32\CSCRIPT.EXE, describes the location of the CSCRIPT executable on my computer. If you have Windows NT loaded in a different directory than C:\WINNT, obviously the command should be modified to reflect this. It is important to provide a fully qualified path to the executable to eliminate the risk that the Scheduler service will not be able to find CSCRIPT.EXE. The second part of the batch command is simply the call to the script file, DIR.VBS. This, too, should be identified with the script’s fully qualified path to prevent a FILE NOT FOUND error. Finally, the > C:\DIR.TXT tells the computer to output the results of the script to a file named DIR.TXT. To recap, you have the modified script file located in the root of C:\ , and it is named Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com in the root of C:\. Ready? It’s time to schedule the task. Schedule the task so that it occurs every Thursday at 5:00 p.m. Open a Command Prompt window and type AT 17:00 /EVERY:W "CMD /C C:\DIR.BAT" You should receive a response from AT that is similar to the one shown in Figure 7.26. Figure 7.26: A successful task entry submission using AT. Now, every Wednesday at 5:00 p.m., the script will run and output a list of files that exist in C:\TEMP to a file named DIR.TXT. This is a straightforward example, but it effectively relates the potential that exists to automate "real life" activities. You could, for example, schedule a script to run a weekly CHKDSK and save the results to a text file. Tip Tasks executed using AT run in the context of the Scheduler service. This means that the scripts you schedule will be executed using the permissions and privileges available to the Scheduler service. If you have trouble running a scheduled task, it is a good idea to see whether the problem stems from a lack of permissions to perform what is being requested. Summary Well, folks, you made it. By now, you have successfully scheduled WSH tasks on both the Windows 95 and NT 4.0 environments. You have also learned about .WSH files and their purpose; CSCRIPT and WSCRIPT, and their options; and a smattering of how these WSH scripts compare with their Web-based cousins. I’ve been watching you, and you have paid attention marvelously. You all get an A. Q&A Q CSCRIPT is the default application chosen by Microsoft. Why would I want to change it? A Feature differences aside, you might want to run your script without the nagging Command Prompt window appearing and disappearing every time a script is run. From a functionality standpoint, the two applications are generally the same. Q I’m creating a script for a mixed- client base, both Windows 95/98 and NT. What precautions should I take to make sure that the script will run in all environments? Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com A Aside from the obvious differences in how scripts are scheduled, most scripts should operate effectively in both environments. This advice is provided with the caveat that scripts should be tested in all environments in which they will be deployed—it's a very prudent programming practice. Q I’ve created a script and tested it thoroughly. When I deploy it, my Windows NT clients cannot execute it. What’s wrong? A Well, there can be a number of reasons why, but I would first check the permissions. If your Windows NT client's hard disk is using the NTFS file system, it's possible that the file level permissions are getting in the way and preventing the script from being run in the user's context. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Week 2: Days 8 to 14 Day List Day 8: Testing and Debugging WSH Scripts Day 9: Handling WSH Script Arguments and Reading/Writing Files Day 10: Replacing Batch Files with WSH Scripts Day 11: Administering User Logins, Program Settings, Folders, and File Shortcuts Using WSH Day 12: Automating Microsoft SQL Server Administration Using WSH Scripts Day 13: Automating Microsoft IIS Administration Using WSH Scripts Day 14: Overview of WSH and Application Scripting Capabilities Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Day 8: Testing and Debugging WSH Scripts By Michael Morrison Overview For most programmers new to scripting, the testing phase of script development is often the most fun. Who can argue the thrill of seeing the results of your hard work? Unfortunately, scripts often don’t behave as you would like them to, especially in early tests. As much as we might think we’re conscientious and thorough enough to never make mistakes when developing scripts, the reality is that scripting is just another facet of programming, and programming is an inherently error-prone process. Bugs in scripts are no less insidious than bugs in full-fledged programming languages such as C++ and Java. Today you’ll learn the following: • Types of errors that can occur in script code • How to perform simple debugging using message box windows • How to use the Microsoft Script Debugger • How to deal with bugs in JScript and VBScript code • Common script bugs and how to avoid them Script Debugging Basics A bug is simply a coding error that results in some unwanted action that takes place in a program. Any bug-free program became that way through thorough testing and debugging. The main difference between good programmers and great programmers is the degree to which they actively set out to uncover bugs as they are developing and testing a program. This brings me to the first rule of debugging, which is to assume that your code has bugs and that it is your responsibility to hunt them down and fix them to the best of your ability. For the purposes of debugging scripts, it is helpful to classify different types of bugs, or errors. Following are the three main types of errors that you'll encounter when creating scripts: • Syntax errors • Runtime errors • Logic errors Syntax Errors Syntax errors are errors that occur because a script violates the fundamental syntax of the JScript or VBScript languages. For example, misspelling a keyword and forgetting to close a block statement are good examples of syntax errors. Syntax errors are also known as load-time errors because they reveal themselves when you first load a script; the script interpreter will catch the error, display an error message, and refuse to run the script. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Note Syntax errors are also sometimes referred to as pre-processor errors, compilation errors, or compile-time errors, even though scripts technically are never compiled. Fortunately, syntax errors are the easiest errors to find and fix because you are always notified of them. Besides, syntax errors are usually the result of accidental oversights or typographical errors as opposed to serious script design errors. Following is an example of a common syntax error: function howdy() { alert("Howdy!") Notice that the closing curly brace (}) is missing in this example. Windows Scripting Host is quick to point out such syntax errors when it first loads a script. Figure 8.1 shows what happens if you forget an enclosing curly brace as was done in this sample code. Figure 8.1: A syntax error displayed in Windows Scripting Host as a result of forgetting an enclosing curly brace in a JScript program. As you can see in the figure, WSH provides you with some information to help track down the error. More specifically, you are given the line number in the script where the error occurred, along with the type of error (compilation error) and a brief description of the error. Keep in mind that WSH isn’t always accurate in pointing out syntax errors. Depending on the specific error, WSH might incorrectly point out the line number. Even so, you should still be able to home in on the error. Runtime Errors The second type of error encountered in script programming is the runtime error. A runtime error is an error that is only revealed when a script is executing, or running. Runtime errors don’t violate script syntax, which is why it isn’t possible for WSH to detect them on first loading a script. Whereas syntax errors are generally caused by violations of script syntax, runtime errors typically involve improper use of commands. For example, a common runtime error is referencing a variable that hasn’t been initialized. Consider the following example: circumference = 2 * 3.14 * radius; In this case, the radius variable is uninitialized, so it is impossible to perform the calculation. Unfortunately, runtime errors are not automatically caught and displayed by WSH. Typically, a script containing a runtime error will simply stop running and do nothing. This makes it significantly more difficult to track down runtime errors without using outside help. Outside help in this case is a special program called a debugger that helps you hunt down bugs. You learn how to use a debugger later in this lesson. Note Runtime errors aren’t all created equal. In fact, VBScript and JScript differ in Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com terms of what they each consider runtime errors. For example, attempting to divide by zero results in a runtime error in VBScript, but not in JScript. Logic Errors The last of the three scripting types is the logic error, which is a functional error that doesn’t disrupt the actual operation of a script. A logic error is caused when code executes without syntax or runtime errors, but the results are not what you intended. Generally speaking, logic errors are a result of the programmer not properly implementing an algorithm. For example, you might have a calculation that is dependent on a user-entered value. However, no matter what the user enters, the result is always the same. After closer inspection, the code reveals that the calculation had a hard- coded constant instead of the variable holding the user entry. You can think of a logic error as an error caused by an inconsistency between your intentions and the actual code implementation. We’re all capable of creating logic errors even after fully thinking through a solution. I’m guilty of committing the error in the sample scenario I just presented. Logic errors are perhaps the most insidious of the three error types because there is no way to absolutely pinpoint the problem. Syntax and runtime errors will both generate alert messages to help you find the problem, but with logic errors, you are left to your own devices. However, a debugger goes a long way toward helping you track down logic errors. You’ll learn some techniques throughout the remainder of the lesson to rein in logic errors, as well as avoid errors in general. Message Debugging In a moment, you’ll learn how to use a debugging tool to perform powerful bug hunting operations. Although debugging tools ultimately provide the best solution for tracking down bugs, there is a simpler approach that you might find useful in some situations. I’m referring to message debugging, which involves using a message box to display information about the state of a script at critical points in the code. Admittedly, this technique is somewhat archaic, but if you want a quick look into what’s going on in a script, it’s not a bad start. Message debugging is carried by simply sprinkling calls to MsgBox() or WScript.Echo() at appropriate locations in your code, depending on whether you’re using VBScript or JScript. If you’re testing JScript code in a Web browser, you can use the alert() function instead of WScript.Echo(). You can use this technique for anything from looking at the value of variables to determining when or whether a function is being called. The results are extremely simple to interpret because you’ll be presented with a message box window each time something important happens in your script. The Script Debugger To help make the detection of bugs easier, Microsoft has Script Debugger, which is freely available for debugging both JScript and VBScript code. The Script Debugger is a standalone application that is used to coordinate the debugging of a script that is executing in a Web browser, such as Internet Explorer. Wait a minute, what does Internet Explorer have to do with WSH? Well, as you probably know, JScript and VBScript both originated as scripting technologies for creating interactive Web pages. Not surprisingly, Web pages are still where the majority of scripting still takes place. Microsoft’s Script Debugger focuses on the debugging of scripts executing within a Web page. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com that you won’t be able to debug all WSH scripts using the Script Debugger. More specifically, you can’t use WSH-specific objects, such as the WScript object, because the Internet Explorer object model doesn’t support WScript. However, the core JScript and VBScript object models are supported under Internet Explorer, so you still have some flexibility when it comes to debugging scripts. Preparing WSH Scripts for the Script Debugger One significant issue related to the WScript object is that of displaying information in a script. If you recall, the Echo() method is called on the WScript object to display a text message in a window from WSH scripting code. Because the WScript object isn’t supported in Internet Explorer, you can’t display information using the Echo() method when debugging scripts. Instead, you can use the alert() function, which also accepts a string argument. Because the Script Debugger operates in terms of a script executing within a Web page, it expects all scripts to be included as part of a Web page’s code. This means that to debug a WSH script in the Script Debugger, you need to copy and paste the script’s code into a Web page with a .html filename extension. The good news is that you only need a couple of lines of HTML code to house the script code. Following is an example: <SCRIPT LANGUAGE="JScript"> alert("Hello there!"); </SCRIPT> In this example, the single line of script code is enclosed between the <SCRIPT> and </SCRIPT> HTML tags. Notice also that the scripting language is set using the LANGUAGE attribute of the <SCRIPT> tag. You should set this attribute appropriately based on whether you’re using VBScript or JScript. The Script Debugger’s dependency on Web page scripts is certainly something that makes WSH script debugging a little trickier. However, it’s worth the extra effort to be able to utilize debugging techniques afforded by using the Script Debugger. Using the Script Debugger Now that you understand how to prepare a WSH script for debugging using the Script Debugger, take the debugger for a test drive. Following is the code for a Web page named FreeSpace.html that includes a debugger-friendly version of the FreeSpace script you created back in Day 6, "Using Microsoft JScript with WSH" : Listing 8.1 Script for FreeSpace.html <SCRIPT LANGUAGE="JavaScript"> alert(GetFreeSpace("c:\\")); function GetFreeSpace(drivePath) { var fso, drive, freeSpace; fso = new ActiveXObject("Scripting.FileSystemObject"); drive = fso.GetDrive(fso.GetDriveName(drivePath)); freeSpace = "Free Space on drive " + drivePath + " : " + Math.round(drive.FreeSpace / 1048576) + " MB"; return freeSpace; Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com } </SCRIPT> The only change to the script code is the replacement of the WScript.Echo() method call with a call to alert() in the first line of script code. The <SCRIPT> and </SCRIPT> tags were also added to satisfy the Web browser. With the script ready for the debugger, the next step is to open the FreeSpace.html Web page in a Web browser. The script immediately runs, in which case you should go along with it and allow it to execute once. After loading the script in a Web browser, you can launch the Script Debugger and get things started. If you have the Script Debugger properly installed, you can launch it by selecting Script Debugger, Open from the View menu in Internet Explorer. Note I’ve had trouble launching the Script Debugger using the menu command in Internet Explorer. If you have a similar problem, you can also launch the Script Debugger manually from Windows Explorer. An alternative approach to running the Script Debugger is to launch it (MSSCRDBG.EXE) manually from Windows Explorer. When the debugger is up and running, select Running Documents from the View menu. A window similar to that in Figure 8.2 then appears. Figure 8.2: The Running Documents window in the Script Debugger. Click to open the Microsoft Internet Explorer tree, which will then display the different documents open in Internet Explorer (see Figure 8.3). Figure 8.3: The Internet Explorer documents available for debugging in the Script Debugger. Double-click the FreeSpace.html document to open it in the debugger (see Figure Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 8.4). Figure 8.4: The FreeSpace.html document open for debugging in the Script Debugger. Select Break At Next Statement from the Debug menu to get the debugger ready. Now return to Internet Explorer and refresh (reload) the FreeSpace.html page. The Script Debugger immediately becomes active, and the first line of code in the script is highlighted as in Figure 8.5. Figure 8.5: The FreeSpace.html halted in the Script Debugger. At this point, the script is halted in the debugger, and you are ready to employ one of a number of debugging techniques, described in the following sections: • Breakpoints • Single-stepping • Variable access • The call stack Halting Scripts with Breakpoints A breakpoint acts somewhat like a roadblock for program execution. It works like this: You place breakpoint on a line of code, and when the script runs and gets to that line of Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]...à script by PDF Merge and Split Unregistered Version - http://www.simpopdf.com Simpo halting the script at the first line of code However, the Script Debugger gives you the freedom to place breakpoints anywhere within a script. à à à à To understand the significance of breakpoints, imagine that you are interested in seeing what happens in a script at a particular point in the code One... in the window in Figure 8.11 being displayed.à à Ãà à à à à à à à à à à à à à à à à Figure 8.11: The modified output of the FreeSpace script. à à Ãà à à à One other interesting point about the Script Debugger’s Command Window is that you can enter any script command directly in the Command Window and see the results For example, entering the following line of code in the Command Window creates and initializes... these single-step approaches is how they handle function calls You'll find menu commands for each of these approaches under the Debug menu in the Script Debugger Try single-stepping once in the FreeSpace script to see how the highlight moves down a line of code in the Script Debugger.à à Accessing Variablesà à Another Script Debugger debugging technique involves accessing variables In general, setting... returns to the Script Debugger, where the highlight now rests on the line of code with the breakpoint, as in Figure 8.8.à à Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com à à à à à à Figure 8.8: The FreeSpace script halted at a breakpoint.à à Ãà à à à Executing One Line at a Timeà à Single-stepping is the process of executing a script a line at a time, in single steps, and... than just trying to take medicine for an illness after the fact, you try to avoid getting sick in the first place Bug prevention in scripting works in a similar way by trying to initially avoid introducing bugs into a program.à à As logical as bug prevention might sound, a surprising number of programmers don’t employ enough bug prevention strategies in their code, and they pay for it later in the debugger... mechanism in that it involves the detection and resolution of unexpected events that take place while a script is running, such as running out of memory Exception handling is built into version 5.0 of JScript An exception is defined as something (usually bad) that occurs in your program that you weren’t expecting In general, you can think of an exception as a type of runtime error.à à To handle exceptions in. .. all debugging strategies The significance of single-stepping as a debugging technique is that it provides you with a way to see and control exactly what code is being executed, which in turn gives you insight into the flow of execution through a script Typically, single-stepping through code isn’t entirely useful by itself; you usually combine it with another debugging technique known as accessing variables... This list can prove extremely valuable in more complex scripts where you have function calls within function calls.à à Dealing with Bugsà à Although debugging certainly plays a vital role in eliminating bugs from your scripts, there is another line of defense that in many ways is more valuable I’m referring to bug prevention, which involves you trying to conscientiously avoid bugs before they’re ever... function You can test the code by changing the number passed into the NumTest() function.à à VBScript and the Err Objectà à JScript isn’t alone in providing special features for dealing with runtime errors VBScript provides a very different approach to handling errors, but one that is useful all the same The intrinsic Err object in VBScript is used to encapsulate information about a runtime error When... misspell certain words in the English language more than others, script programmers have a tendency to make certain coding mistakes that result in bugs By understanding these common mistakes, you’ll be better equipped to avoid them in your own scripts Following is my list of common scripting bugs that you should try hard to avoid:à à •Ãà Assuming the wrong operator precedenceà à •Ã Accidentally using the . error displayed in Windows Scripting Host as a result of forgetting an enclosing curly brace in a JScript program. As you can see in the figure, WSH provides you with some information to help. debugging using message box windows • How to use the Microsoft Script Debugger • How to deal with bugs in JScript and VBScript code • Common script bugs and how to avoid them Script Debugging. http://www.simpopdf.com Figure 8.8: The FreeSpace script halted at a breakpoint. Executing One Line at a Time Single-stepping is the process of executing a script a line at a time, in single steps, and represents

Ngày đăng: 13/08/2014, 08:21

TỪ KHÓA LIÊN QUAN