sams teach Yourself windows Script Host in 21 Days phần 7 doc

51 348 0
sams teach Yourself windows Script Host in 21 Days phần 7 doc

Đ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

à à à Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Listing 13.2 Using createweb.vbs to Create a Web Siteà à ’ FILE: createweb.vbsà ’ DESC: This script illustrates how you can programmaticallyà ’ create a web site using IIS administration objects.à ’ AUTH: Thomas L Fredellà ’ DATE: 11/23/98à ’à ’ Copyright 1998 Macmillan Publishingà à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à Dim Dim Dim Dim à à à à à à On Error Resume Nextà à à à à Option Explicità à à à à à oArgs, sComputer, sHostName, sRootDirà oService, nNewServer, oServer, oVDir, oDirà oFS, sBasePath, sCGIDirà sTmpà à ’ Step 1: Check script argumentsà Set oArgs = Wscript.Argumentsà If oArgs.Count Thenà Wscript.Echo "USAGE: createweb [computer] [hostname]" & _à " [instance] [rootdir]"à Wscript.Echo ""à Wscript.Echo " Creates a new IIS web site on "à Wscript.Echo " [computer] using the [hostname]."à Wscript.Echo " [instance] specifies the web server"à Wscript.Echo " and [rootdir] specifies the root"à Wscript.Echo " directory on the file system."à Wscript.Echo ""à Wscript.Quit 1à End Ifà sComputer = oArgs(0)à sHostName = oArgs(1)à nNewServer = oArgs(2)à sRootDir = oArgs(3)à à ’ Step 2: Get the object that represents the web serviceà Set oService = GetObject("IIS://" & sComputer & "/W3SVC")à à ’ Step 3: Create a new virtual serverà ’ Determine the new virtual server number byà à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à ’Simpo PDF Merge and Split Unregistered Version iterating through the current serversà oService.GetInfoà Set oServer = oService.Create("IIsWebServer", nNewServer)à If Err.Number Thenà ShowErr "Unable to create server."à Wscript.Quit Err.Numberà End Ifà à - http://www.simpopdf.com à ’ Step 4: Configure the new serverà oServer.DefaultDoc = "default.htm, index.htm"à oServer.ServerComment = "New server created by createweb.vbs"à oServer.ConnectionTimeout = 600à oServer.ServerBindings = ":80:" & sHostNameà oServer.SetInfoà If Err.Number Thenà ShowErr "An error occurred while setting configuration params."à Wscript.Quit Err.Numberà End Ifà à ’ Step 5: Create virtual root directory for the new siteà Set oVDir = oServer.Create("IIsWebVirtualDir", "ROOT")à If Err.Number Thenà ShowErr "Unable to create virtual root directory."à Wscript.Quit Err.Numberà End Ifà à ’ Step 6: Configure the virtual root directoryà Set oFS = CreateObject("Scripting.FileSystemObject")à sBasePath = oFS.GetAbsolutePathName(sRootDir)à oVdir.Path = sBasePathà oVdir.AccessRead = Trueà oVdir.AccessWrite = Trueà oVdir.AccessScript = Trueà oVdir.SetInfoà If Err.Number Thenà ShowErr "Unable to save settings for virtual root."à Wscript.Quit Err.Numberà End Ifà oVdir.AppCreate Falseà If Err.Number Thenà ShowErr "Unable to define virtual root as application."à Wscript.Quit Err.Numberà End Ifà oVdir.SetInfoà à ’ Step 7: Create and configure a cgi-bin directoryà ’ First ensure that the physical directory existsà à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à sCGIDir PDF Merge and Split Unregistered Version Simpo = sBasePath & "\cgi-bin"à If Not oFS.FolderExists(sCGIDir) Thenà ’ Create the physical cgi-bin directoryà oFS.CreateFolder sCGIDirà End Ifà à - http://www.simpopdf.com à ’ Then create the IIsWebDirectory object & configure ità Set oDir = oVDir.Create("IIsWebDirectory", "cgi-bin")à If Err.Number Thenà ShowErr "Unable to create cgi-bin directory."à Wscript.Quit Err.Numberà End Ifà oDir.AccessRead = Falseà oDir.AccessWrite = Falseà oDir.AccessScript = Trueà oDir.AccessExecute = Trueà oDir.SetInfoà If Err.Number Thenà ShowErr "Error setting cgi-bin configuration."à Wscript.Quit Err.Numberà End Ifà à ’ Step 8: Start the web serverà oServer.Startà If Err.Number Thenà ShowErr "Unable to start new web server."à Wscript.Quit Err.Numberà End Ifà à ’ Step 9: Done! Quit executionà Wscript.Echo "createweb.vbs: Successfully created new web site."à Wscript.Echo "createweb.vbs: Instance #=" & nNewServerà Wscript.Echo "createweb.vbs: Host Name=" & sHostNameà Wscript.Echo "createweb.vbs: Root Dir=" & sRootDirà Wscript.Quit 0à à ’ à ’ SUB: ShowErr(Description)à ’ DESC: Displays information about a runtime error.à ’ à Sub ShowErr(sDescription) à Wscript.Echo "createweb.vbs: " & sDescriptionà Wscript.Echo "createweb.vbs: An error occurred code: " & _à Hex(Err.Number) & " - " & Err.Descriptionà End Subà à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à You can see the output of the script from the command line in Figure 13.8 If you go to the Microsoft Management Console, illustrated in Figure 13.9, you’ll notice that a new Web site has been created.à à à Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com à à à à à à Figure 13.8: The command-line output of createweb.vbs.à à Ãà à à à à à à à Figure 13.9: The resulting Web site in the Microsoft Management Console.à à Ãà à à à Comments in the script divide the script into different steps Step one ensures that the proper arguments have been specified for the script That’s a standard step that will be included in any of the sample scripts that take arguments Step two retrieves the Web service object using an ADSI path; it uses the GetObject() function that’s standard for accessing the IIS administrative objects Step three creates a new Web server object using the instance number specified on the command line.à à Step four sets some of the properties for the Web server There are many properties to choose from; if you examine the code for the first example, you’ll see a list of them Step five creates a new virtual root directory for the Web site, and in step six, it is configured For the configuration, you set the path for the root directory, then you set access rights, and finally you set it up as an out-of-process application.à à à à à à Step creates and configures the cgi-bin directory First the code checks to ensure that the physical cgi-bin directory actually exists If the physical directory doesn’t exist, it is created using the FileSystemObject that was à describedPDF Merge and Split Unregistered cgi-bin is http://www.simpopdf.com Simpo in Day Next a Web directory object for Version - created, and the access rights are set The only access that you’ll enable is script and execute access That’s plenty of access for the cgi-bin directory and this will ensure that no one downloads any CGI executables that you put in the directory.à à à à Finally, step starts the Web server; you check to ensure that it actually starts by validating that no error occurs Step stops execution and displays information about the site that was created.à à The script is relatively simple For the most part, you use the standard ADSI methods to create new objects You also use some of the IIS specific properties to set configuration parameters You can modify it for your purposes by creating different objects, such as different directories, or by setting different properties.à à Scanning Sites for Configuration Settingsà à One of the benefits of using WSH scripts to administer IIS Web servers is that you can perform automated tasks that would be infeasible or impractical using the standard Management Console The script example shown in Listing 13.3 illustrates a task that would be difficult if not automated The following script, scanweb.vbs, scans a Web site and determines whether any EXE files are located within directories with either access read or access write permissions set.à à The scanweb.vbs script takes the following arguments, in order: computer—this is the name of the computer that contains the Web site to scan, and hostname—this is the hostname of the Web site that you want to scan.à à Listing 13.3 Using scanweb.vbs to Find Configuration Settingsà à ’ FILE: scanweb.vbsà ’ DESC: This script illustrates how you can programmaticallyà ’ scan a web site using IIS administration objects.à ’ AUTH: Thomas L Fredellà ’ DATE: 11/23/98à ’à ’ Copyright 1998 Macmillan Publishingà à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à Dim Dim Dim Dim à à à à à à On Error Resume Nextà à à à à Option Explicità à à à à à oArgs, sComputer, sHostNameà oService, oServer, oVDir, oFSà sBindings, sToFind, tFoundà sTmpà à ’ Step 1: Check script argumentsà Set oArgs = Wscript.Argumentsà à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à If oArgs.Count and Split Unregistered Version - http://www.simpopdf.com à Simpo PDF Merge Thenà Wscript.Echo "USAGE: scanweb [computer] [hostname]"à à Wscript.Echo ""à à Wscript.Echo " [computer] = this is the à computer to scan"à Wscript.Echo " [hostname] = this is the à hostname to scan"à Wscript.Echo ""à à Wscript.Echo " This scans an IIS web site to à determine if"à Wscript.Echo " executable programs are in à directories"à Wscript.Echo " that have read or write à access."à Wscript.Echo ""à à Wscript.Quit 1à à End Ifà à sComputer = oArgs(0)à à sHostName = oArgs(1)à à à ’ Step 2: Get the object that represents the web serviceà Set oService = GetObject("IIS://" & sComputer & "/W3SVC")à à ’ Step 3: Find the specific web serverà oService.GetInfoà sToFind = ":" & sHostName & ":"à tFound = Falseà For Each oServer In oServiceà sBindings = Join(oServer.ServerBindings, ":") & ":"à ’ sBindings should now be a string in the form:à ’ IP1:Port1:Hostname1:IPn:Portn:Hostnamen:à If Err.Number Thenà Err.Clearà Elseà tFound = (InStr(sBindings, sToFind) > 0)à If tFound Then Exit Forà End Ifà Nextà If Not tFound Thenà Wscript.Echo "scanweb.vbs: Unable to find hostname."à Wscript.Quit 1à End Ifà à ’ Step 4: Get the ROOT directory for the siteà Set oFS = Wscript.CreateObject("Scripting.FileSystemObject")à Wscript.Echo "scanweb.vbs: Beginning scan on " & sHostNameà Wscript.Echo ""à Set oVDir = oServer.GetObject("IIsWebVirtualDir", "ROOT")à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à If Err.Number 0and Split Unregistered Version Simpo PDF Merge Thenà ShowErr "Unable to get root directory."à Wscript.Quit Err.Numberà End Ifà à - http://www.simpopdf.com à à à à à à à à à à ")"à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à If oDir.Class = "IIsWebVirtualDir" Thenà sThisParentPath = oDir.Pathà Elseà sThisParentPath = sParentPath & "\" & oDir.Nameà End Ifà Wscript.Echo "Scanning " & oDir.ADsPath & " "à Wscript.Echo " " & "(" & sThisParentPath & à à à à ’ à ’ SUB: ScanDir(oDir)à ’ DESC: Scans a directory for executable files, thenà ’ checks directory access permissions.à ’ à Sub ScanDir(oDir, sParentPath)à Dim objà Dim tReadOrWriteà Dim sThisParentPathà à à à à ’ Step 6: Done! Quit executionà Wscript.Echo ""à Wscript.Echo "scanweb.vbs: Site scan complete."à Wscript.Quit 0à à à à à ’ Step 5: Recursively iterate through the directory & allà ’ sub-directories, checking for EXE filesà ScanDir oVDir, ""à à à à à à à à à à à à ’ Check if we need to examine this directory for exe filesà If oDir.AccessRead Or oDir.AccessWrite Thenà ’ This is a read or write directory, so check for exeà Dim oFolderà Dim oFilesà Dim oFileà Dim iFileà à à à à à à à à à ’ We scan files using a FileSystemObject, becauseà ’ we may not get IIsFile objects for every fileà Set oFolder = oFS.GetFolder(sThisParentPath)à If Err.Number Thenà ShowErr "Unable to get folder ’" & _à sThisParentPath & "’."à à à à à à à à à Err.Clear à Simpo PDF Merge andà Split Unregistered Version - http://www.simpopdf.com Elseà ’ Scan files within the directoryà Set oFiles = oFolder.Filesà For Each oFile In oFilesà If InStr(UCase(oFile.ShortName), ".EXE") à à à à à à à à à à > Thenà à à " & _à à à contains a exe"à Wscript.Echo " "read or write directory Exit Forà End Ifà à à à à à à à à à à à à à à à à à à à à Nextà If Err.Number Thenà ShowErr "An error occurred while checking files."à Err.Clearà End Ifà End Ifà End Ifà à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à Wscript.Echo ""à à à à à WARNING: This à à ’ Finally we recurse and check sub-directoriesà For Each obj In oDirà Select Case obj.Classà Case "IIsWebVirtualDir"à ScanDir obj, sThisParentPathà Case "IIsWebDirectory"à ScanDir obj, sThisParentPathà End Selectà Nextà End Subà à ’ à ’ SUB: ShowErr(Description)à ’ DESC: Displays information about a runtime error.à ’ à Sub ShowErr(sDescription)à Wscript.Echo "scanweb.vbs: " & sDescriptionà Wscript.Echo "scanweb.vbs: An error occurred - code: " & _à Hex(Err.Number) & " - " & Err.Descriptionà End Subà à à à à à à à à à à à à à à à à à à à à à à à à à à The scanweb.vbs script enables you to specify a computer and a hostname to begin a site scan You’ll run it on the sample Web site that you created with the previous script, after you’ve added some EXE files Figure 13.10 shows a directory listing of the Web site that you’re going to scan The results of the scan are illustrated in Figure 13.11.à à Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com à à à à à à Figure 13.10: The directory listing of the Web site that will be scanned.à à If you examine how the script functions, you’ll notice that it begins with the typical check for correct command-line parameters in step In step 2, you get an object for the IIsWebService on the specified computer In step 3, you iterate through all the IIsWebServer objects associated with the IIsWebService until a Web server is found that matches the hostname specified on the command line The hostname check is done using the ServerBindings property; ServerBindings is a list of strings in the form "IP address:Port number:hostname".à à Next, in step 4, assuming that you found the correct Web server, you access the root directory of the Web server Just before you access the root directory, you instantiate a WSH FileSystemObject The FileSystemObject will be used when you scan directories for the files that they contain You begin the directory scanning by calling the ScanDir() function in step 5.à à ScanDir() is where most of the work occurs in this script It first determines the path for the current directory that is being scanned If the current directory is a virtual directory, the Path property returns the correct physical file directory However, if it is a standard directory, in other words an IIsWebDirectory object, it does not have a Path property Consequently, you must append the value of the Name property to the parent path to calculate the physical directory Next, a message is displayed that indicates the directory and physical file folder that is being scanned The AccessRead and AccessWrite properties of the directory are checked to determine whether either is enabled If either is enabled, the physical file directory is scanned for files with the extension EXE If a file is found with the EXE extension, a warning message is printed The example illustrated in Figure 13.11 shows the warning message.à à Ãà à à à à à à à à à Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com à à à à à à Figure 13.11: The output from the scanweb.vbs script.à à Ãà à à à The last part of the ScanDir() function causes the recursion If the directory contains any IIsWebDirectory or IIsWebVirtualDir objects, the ScanDir() function is called with the subdirectory.à à The script finishes execution when there are no more directories upon which to call ScanDir() Step simply outputs a "finished" message and then calls the standard Wscript.Quit() function.à à Performing Mass Changes to Groups of IIS Web Sitesà à Listing 13.4 shows how you can perform mass changes to groups of IIS Web sites You’ll provide a put function that enables you to put a specific file within a directory that matches a regular expression search criterion This time you’ve implemented the script using the JScript language because the language contains inherent support for regular expression searches.à à à à à à à à à à à à à à The name of the script is putfile.js, and you can refer to the source code in Listing 13.4 The script takes the following arguments, in order: computer—this is the name of the computer that contains the Web site; à instance—this is the instance number of the Web site; file—this is the file that you want to put on the Web site; and direxp—this is a regular expression that will be used to match directories.à à à à Listing 13.4 Using putfile.js to Change Web Site Groupsà à // FILE: putfile.jsà // DESC: This script illustrates how you can programmaticallyà // replace a file within a web site using IISà // administration objects.à // AUTH: Thomas L Fredellà // DATE: 11/24/98à //à // NOTE: This script uses JScript for regular expressionà // functionality, so consequently, with this à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com There are also some useful methods defined in the Worksheet object One of these methods is Calculate(), which is used to calculate a worksheet, or a range of cells within a worksheet The following code shows how to calculate a worksheet by calling the Calculate() method:à à appXL.ActiveSheet.Calculate()à à If you happen to have a worksheet with some text in it, you might consider spellchecking the worksheet The CheckSpelling() method does just the trick:à à appXL.ActiveSheet.CheckSpelling()à à The Excel Range Objectà à Although you can use the Cells property of a worksheet to access individual cells, the real power of accessing worksheets comes in the form of the Range object The Range object represents a range of cells and is used throughout the Excel object hierarchy to represent a selection of cells The Range object is not exactly a collection, but it can certainly represent multiple cells This makes the Range object somewhat unique because it can represent either a single cell or range of cells.à à Perhaps the simplest way to use the Range object is to access an individual cell using the name of the cell in Excel’s A1-style naming convention This naming convention uses letters for the column names and numbers for the row names, as displayed in Excel The following sets the value of an individual cell using the Range object:à à appXL.ActiveSheet.Range("B3").Value = 23à à This code sets the cell at location B3 to 23 You can also set a cell to a formula by providing the formula as a string for the Formula property, like this:à à appXL.ActiveSheet.Range("B4").Formula = "=(B3 - 8) / 5"à à The real power of ranges doesn’t enter the picture until you start dealing with ranges of cells Here’s how to initialize a two-dimensional range of cells to zero:à à appXL.ActiveSheet.Range("A1:E5").Value = 0à à Alternatively, you might want to clear a range of cells instead of setting them to zero:à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à appXL.ActiveSheet.Range("A1:E5").ClearContents()à Scripting Microsoft Wordà à à à à à Because all Office applications adhere to a similar object model, you will find that scripting Word is very similar to scripting Excel The primary difference between scripting each of these applications has to with their each operating on very different types of data Even so, the manner in which objects are handled is very similar when scripting all Office applications For example, the Application object is used as the application for both Word and Excel These are some of the most important objects you will encounter when scripting Word:à à •Ãà Applicationà à à Ãà à à Ãà à •Ãà Documentà Simpo PDF à Merge and Split Unregistered Version - http://www.simpopdf.com à Ãà à •Ãà Rangeà à •Ãà Selectionà à •Ãà Find and Replacementà à Similar to its role in the Excel object model, here the Application object represents an instance of a Word application session The Application object also serves as the basis for navigating through the object hierarchy and obtaining references to other objects such as Document objects The Document object is somewhat akin to the Workbook object in Excel and represents a Word document The Range object represents a selection of one or more contiguous text elements in a document Although these elements could be words, sentences, or paragraphs, it's more accurate to think of a Range object as representing a series of characters The Selection object is similar to the Range object except that it applies to the currently selected text in a document; the text selected in a Range object doesn't affect the document selection.à à The Find and Replacement objects encapsulate the criteria required to perform a find and replace operation The information stored in these objects reflects the options in the standard Find and Replace dialog box.à à The Word Application Objectà à The Application object in Word functions very much like the Application object for Excel In the context of Word, the Application object contains a collection of documents in the Documents property The Application object also includes a Windows property that is a collection of child windows open in the application.à à You obtain a reference to a Word Application object by calling the CreateObject() method on the WScript object and passing "Word.Application" as the only argument:à à à Ãà à à Ãà à à à à à à à à à à à à à à à à à à à à à à à Dim appWordà Set appWord = WScript.CreateObject("Word.Application")à appWord.Visible = Trueà à à à à à à You must set the Visible property of the Application object to True to make sure that the application window is visible.à à Not surprisingly, the Application object contains a wide range of properties and methods that can be used to automate Word and perform interesting tasks These are some of the more commonly used properties of the Application object:à à •Ãà Windowsà à •Ãà Documentsà à •Ãà ActiveWindowà à •Ãà ActiveDocumentsà à •Ãà Optionsà à à à à à Ãà à à Ãà à à Ãà à à Ãà à à Ãà à à à The Windows object is and Split Unregistered Version - http://www.simpopdf.com Simpo PDF Merge a collection of Window objects representing open windows in the current Word application session You obtain references to individual Window objects by à indexing the Windows collection or by using the ActiveWindow property This code displays the caption of the first window in the Windows collection:à à à à MsgBox(appWord.Windows(1).Caption)à à You can also close a window by calling the Close() method on a Window object The following closes the active window by calling Close() on the ActiveWindow property:à à appXL.ActiveWindow.Close()à à At this point, you probably realize how similar the script code is for various Office applications The reality is that after you’ve learned how to script one Office application, it requires very little additional knowledge to script other Office applications Let’s continue learning the basics of scripting Word!à à The Documents object is a collection of Document objects representing open documents You obtain references to individual Document objects by indexing the Documents collection or by using the ActiveDocument property Here is an example that checks whether changes have been made to necessitate saving the current document:à à à à à à à à à à à à à à à à à à à à à If appWord.ActiveDocument.Saved = False Thenà MsgBox("Somebody please save me!")à End Ifà à à à à à à This code should look familiar because it is very similar to the code you saw earlier that performs a similar function in Excel.à à There are a few capabilities of the Application object that you didn’t learn about in the discussion of Excel For one, you can switch the view to Print Preview by setting the PrintPreview property to True, like this:à à appWord.PrintPreview = Trueà à Simple! You can also control the application’s graphical user interface by getting and setting property values such as DisplayStatusBar, which determines whether the status bar is visible The following code toggles the status bar’s visibility:à à appWord.DisplayStatusBar = Not appWord.DisplayStatusBarà à In addition to controlling the Word application’s appearance, you can also alter the application’s options using the Options property The Options object includes a variety of properties that can be accessed to alter the functionality of Word—for example:à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à With appWord.Optionsà AllowDragAndDrop = Falseà AllowFastSave = Trueà BackgroundSave = Trueà SaveInterval = 15à End Withà à à à à à à à viewed and setMerge and Splitcommand from Word’s Toolshttp://www.simpopdf.com Simpo PDF using the Options Unregistered Version - menu You might want to check out these options in Word to get an idea of the options you can alter programmatically.à à à à The Word Documents Objectà à Like workbooks in Excel, Word documents form the basis of information storage and retrieval in Word All content that you manipulate in Word is saved within the context of a document, which can later be opened To open a document programmatically, you simply call the Open() method on the Documents object, like this:à à appWord.Documents.Open("C:\My Documents\Bio.doc")à à After you’ve opened a document, you’re ready to get to work entering and formatting document data.à à à à à à à à à à à à Ãà à Noteà If you don’t specify a full path when using the Open() method, Word will à assume that the file is in the current folder.à à à à à To give the user a say in what document is opened, you can call the GetOpenFilename() method, which displays the standard File Open dialog box This method returns a string path for the file selected by the user, which you can then pass to the Open() method to actually open the file The following example demonstrates how this is accomplished:à à à à à à à à à à à fileName = appWord.GetOpenFilename()à If fileName False Thenà appWord.Documents.Open(fileName)à End Ifà à à à à à à à To start out with a new document rather than open an existing one, you can use the Add() method on the Documents object Similar to its counterpart in Excel’s Workbooks object, the Add() method in Documents creates an empty document.à à doc = appWord.Documents.Add()à à After making changes to a document, either directly in Word or programmatically from a script, you can save it using either the Save() or SaveAs() methods in the Documents object You should always use SaveAs() when saving a document for the first time, because the document doesn’t yet have a filename The GetSaveAsFilename() method displays the standard File Save As dialog box, which allows the user to browse and enter a filename for the document You can call this method before calling SaveAs() to allow the user to enter the filename The following code saves a document using this approach:à à à à à à à à à à à à à à à à à fileName = appWord.GetSaveAsFilename()à If fileName False Thenà doc.SaveAs(fileName)à End Ifà à à à à à à à The SaveAs() method is called on a variable named doc, which must have been previously set to a Documents object The best place to set such a variable is when you first add or open a workbook You could also use the ActiveDocument property to save the current document, like this:à à à à à à à à à à fileName = Merge and Split Unregistered Version Simpo PDF appWord.GetSaveAsFilename()à If fileName False Thenà appWord.ActiveDocument.SaveAs(fileName)à End Ifà à - http://www.simpopdf.com à à à à à à Closing a document is as simple as calling the Close() method on a Documents object:à à book.Close()à à You can determine how many documents are open in a given Word session by looking at the Count property of the Documents object, like this:à à MsgBox("There are " & appWord.Documents.Count & " documents open.")à à à à à à à à à à à à Ãà à Noteà If you call the Save() or Close() method on the Documents collection, all à the documents in the collection will be saved or closed.à à à à à To print a document, you simply call the PrintOut() method on a Documents object:à à wordApp.ActiveDocument.PrintOut()à à A topic closely related to printing is the setup of the page, which can be altered using the PageSetup property of the Documents object The PageSetup object provides a host of properties that represent the various options available in Word’s Page Setup dialog box This code sets the margins for the active document using the PageSetup property:à à à à à à à à à à à à à à à à à à à à à With appWord.ActiveDocument.PageSetupà LeftMargin = InchesToPoints(0.5)à RightMargin = InchesToPoints(0.5)à TopMargin = InchesToPoints(1.0)à BottomMargin = InchesToPoints(1.0)à End Withà à à à à à à à à à As you’ve already learned, the Documents object is powerful and gives you lots of flexibility when it comes to manipulating Word documents Take a look at one more use of the Documents object before moving on I’m referring to revision marks, which are used in Word as a means of keeping track of document changes You can turn revision tracking on and off by setting the TrackRevisions property, like this:à à wordApp.ActiveDocument.TrackRevisions = Trueà à The Word Range and Selection Objectsà à Because a Word document essentially consists of a group of sequentially arranged formatted characters, you typically manipulate a document by adding or selecting characters The Word object model provides a suite of objects that make the selection and manipulation of text very straightforward Two of the most important classes in this model are Range and Selection Both these objects represent a range of contiguous characters; the difference between them has to with their relationship to Word’s current user selection.à à à à à à à à à à à à à highlight If no text is selected, the Unregistered Version - http://www.simpopdf.com Simpo PDF Merge and Split Selection object represents the insertion point in the document, which is the location of the user input caret Like the Selection object, the Range object also represents a selection of text, but it has no association with the highlighted text selection visible in Word In other words, the Range object is an allpurpose selection object that enables you to select and manipulate text without the selection being visibly highlighted in Word Another difference between ranges and selections is that you can create multiple Range objects, whereas only one Selection object can be active at any given time This makes sense because there can be only one physical selection active in Word.à à à à You can use the Range and Selection objects to perform all kinds of interesting tasks in Word, such as creating paragraphs, inserting text, and applying formatting and font styles You can also use these objects to select a portion of a document to search for a word or phrase Ranges and selections are defined by starting and ending character positions, which are calculated relative to the first character in a document The first character in a document has the character position of zero If a range or selection identifies the insertion point, the starting and ending character positions are equal.à à à Ãà à Noteà The remainder of this section focuses on ranges because they are generally Ãmore flexible than selections However, keep in mind that using the Selection object is very similar to using the Range object.à à à à à A range is identified by three primary properties:à à •Ãà Start—The starting character position for the rangeà à •Ãà End—The ending character position for the rangeà à •Ãà StoryType—The type of story selected by the rangeà à Not surprisingly, the Start and End properties represent the starting and ending character positions of the range The StoryType property is a little more interesting A story is an area of a document that contains text that is distinct from other parts of a document For example, the body, header, and footer are all considered stories The StoryType property can have one of 11 values that identify the story type of the range:à à •Ãà wdMainTextStoryà à •Ãà wdPrimaryFooterStoryà à •Ãà wdPrimaryHeaderStoryà à •Ãà wdFirstPageFooterStoryà à •Ãà wdFirstPageHeaderStoryà à •Ãà wdEvenPagesFooterStoryà à •Ãà wdEvenPagesHeaderStoryà à •Ãà wdFootnotesStoryà à •Ãà wdCommentsStoryà à •Ãà wdEndnotesStoryà à à Ãà à à Ãà à à Ãà à à à à à Ãà à à Ãà à à Ãà à à Ãà à à Ãà à à Ãà à à Ãà à à Ãà à à Ãà à à Ãà à Ãà à •Ãà wdTextFrameStoryà Simpo PDF Merge and à Split Unregistered Version - http://www.simpopdf.com à à à You typically don't have to worry about the story type of a range, so you can move on to working with ranges The following example shows how to apply bold formatting to the first 20 characters in the active document:à à appWord.ActiveDocument.Range(0, 20).Bold = Trueà à As you can see, the range of characters is specified to the Range() method, which returns a Range object The Bold property of this object is then set to apply bold formatting to all the characters in the range Although this example is functional, you typically think of a Word document as a series of words, sentences, and paragraphs, as opposed to individual characters The following example uses a range to italicize the first four words in the active document:à à appWord.ActiveDocument.Range(0, appWord.ActiveDocument.Words(4).End).Italic = Trueà à This example makes use of the Words collection, which references all the words in a document Also, Sentences, Paragraphs, and Sections properties of the Document object allow you to work with sentences, paragraphs, and sections as opposed to words or characters The following code alters the font size of the third sentence in the active document and then inserts a new paragraph before and after the paragraphs:à à à à à à à à à à à à à à à à à à à à à à à Set range = appWord.ActiveDocument.Sentences(3)à range.Font.Size = 40à range.InsertParagraphBefore()à range.InsertParagraphAfter()à à à à à à à à In this example, the Sentences collection is indexed to return a range containing the third sentence in the document.à à Keep in mind that all the range examples you've seen thus far have no effect on Word's text selection I alluded to the fact earlier in the lesson that the Range object is more flexible than the Selection object These are the specific reasons why:à à •Ã You can use multiple Range objects, whereas only one Selection object is allowed à per document window.à à •Ãà Using Range objects doesn't affect the text selected in Word.à à •Ãà Range objects are a little faster to use than the Selection object.à à à à à à Ãà à à Ãà à à Ãà à à Ãà à Noteà Although the main benefit to using ranges is that they don't affect the text selection, you can use the Range object as the basis for selecting text For example, you might want to reflect a range visually, in which case you would à use the range to alter the selection The Select() method in the Range object enables you to accomplish this task by applying a range to the selection.à à à à à Before moving on, you must tackle one last topic related to ranges: looping This example shows how to loop through a range of characters and apply the underline formatting style to each:à à Set range = appWord.ActiveDocument.Words(1)à à à à à à à à à à à à à For i = To 30à and Split Unregistered Simpo PDF Merge range.Underline = Trueà Set range = range.Next(1)à Nextà à Version - http://www.simpopdf.com à à à à à à Here, the Next() method is called to alter the range and select one character after another.à à The Word Find and Replacement Objectsà à You’ve learned how to use the Range object to select specific ranges of text Although this approach certainly has its benefits, you might want to select ranges of text by searching for a particular word or phrase Additionally, you might want to search and replace text in a document The Find and Replacement objects make both these tasks possible If you’ve used the Find or Replace commands in Word, you’ve already seen these objects at work Issuing the Find command in Word is equivalent to calling the Find() method on the Selection object in script code.à à The following example shows how to use the Find() method to locate the next occurrence of the word sneaky:à à à à à à à à à à à à à à à à à à à à à à With appWord.Selection.Findà Forward = Trueà Text = "sneaky"à Execute()à End Withà à à à à à à à à The Forward property of the Find object is first set to True to indicate that the search should be performed forward through the document The search text is set via the Text property Finally, the Execute() method is called to start the search If the end of the document is reached before the search text is found, the search is stopped.à à à à à à à The Replacement object is a property of the Find object, which means that you use the Find object to perform both the find and replace operations The properties in the Find and Replace objects correspond to the options available in Word’s Find and Replace dialog box Keep in mind that you can use the Find object with a range, as well as the selection, which doesn’t affect the visible selection in Word.à Making Sure That Objects Are Validà à Now that you understand how to develop scripts for Excel and Word using their respective scripting object models, it’s important to point out a couple issues regarding runtime errors Because script code regularly uses object references to access objects through properties and methods, it’s possible to generate runtime errors by inadvertently using the wrong object in a given context You can avoid such errors by checking the type of an object before attempting to access it.à à The TypeName() function returns the type of an object The following is an example of checking the type of the object returned by the Add() method in Excel:à à à à à à à à à à à à à à à à à Set book = appXL.Workbooks.Add()à if TypeName(book) "Workbook" Thenà MsgBox("Error adding workbook.")à End Ifà à à à à à à à Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com In this example, you know that the correct return type of the Add() method is Workbook, so you can check to make sure that the type name of the book variable is Workbook before accessing the variable.à à Another trick to help avoid runtime errors is to use the global IsObjectValid property This property applies to all objects and can be used to determine whether an object reference is valid The IsObjectValid property is set to True if an object is valid or otherwise to False An invalid object is one for which no memory has been allocated or for which the memory has already been freed Either way, attempting to use the object will result in a runtime error This code checks the book variable to see whether it is valid:à à if IsObjectValid(book) = Falseà MsgBox("The workbook isn’t valid.")à End Ifà à à à à à à à à à à à Scripting Multiple Office Applicationsà à à à à à à The final topic today pulls together much of what you’ve learned about Microsoft Office scripting in a simple example The topic to which I’m referring is that of controlling multiple Office applications with a single script This is a powerful use of scripting because it enables you to share information between applications Here is a sample script that performs the following steps:à à 1.à à Opens an Excel workbookà à 2.à à Retrieves a value from a cell in an Excel worksheetà à 3.à à Builds a sentence string containing the valueà à 4.à à Creates a Word document and adds the sentence to ità à Dim appWordà Dim appXLà à à Ãà à à Ãà à à Ãà à à Ãà à à à à à à à à à à à à à à à à à à à à à à à à à à à à à Set appWord = WScript.CreateObject("Word.Application")à appWord.Visible = Trueà Set appXL = WScript.CreateObject("Excel.Application")à appXL.Visible = Trueà à appXL.Workbooks.Open("C:\My Documents\Finance\Plan99.xls")à appWord.Documents.Add()à à sentence = "The value is " & appXL.Cells(4, 3).Value & "."à appWord.ActiveDocument.Words(1).InsertAfter(sentence)à à à à à à à à à à à à à à à à à à à This script uses scripting elements that you learned today The only new skill you’re exercising is the ability to merge the scripting of multiple applications within a single script.à à Summaryà à à à This lesson explores the possibilities for using Windows Script http://www.simpopdf.com Simpo PDF Merge and Split Unregistered Version - Host to control and interact with Microsoft Office applications You learned the basics of Office scripting, including how to obtain object references and how to access properties and methods of objects You then learned the specifics of how to write scripts to interact with Excel and à Word, the two most popular Office applications From there, you learned a few tips regarding error prevention Finally, you combined what you learned today to create a script that shares data between Excel and Word.à à à à Keep in mind that today you only scratched the surface of what can be accomplished with WSH and Office Office applications have very extensive object models that offer all kinds of interesting opportunities for scripting My objective today was to lay the groundwork for you to explore these opportunities on your own.à Q&Aà à à à à Ãà à Qà I’ve read through the Visual Basic reference that ships with Word and Excel, à and some of the examples differ from the code in this lesson Why is this?à à Aà The reason for a disparity between the sample code in the Visual Basic documentation for Office applications has to with the applications themselves à supporting the Visual Basic for Applications (VBA) programming language Although VBScript is similar to VBA, VBScript isn’t quite as full featured Therefore, VBScript code is more simplified than VBA code.à à Qà à Can I also use JScript to script Office applications?à à Aà Of course! VBScript and JScript are both fully supported in Office applications I focused primarily on VBScript today just to make things more consistent Besides, à this will make it easier for you to understand the code if you should poke around in the VBA documentation that ships with Office.à à Qà Is there a relationship between scripting code in Word and the code à associated with a Word macro?à à à Ãà à à Ãà à à Ãà à à Ãà à à Ãà à Aà Yes Word macros are actually just VBA programs, which means that they adhere to the same object model used by VBScript and JScript One neat trick to learning how to à carry out certain tasks is to first record a macro and then study the resulting code In many cases, you will be able to convert this code to VBScript without too much work, which will enable the code to run under WSH.à Simpo PDF Merge and Split to Access Databases Day 16: Using WSHUnregistered Version - http://www.simpopdf.com Through Microsoft Active Data Objects (ADO) à à à à à à Overviewà à As you’ve seen throughout this book, the Windows Scripting Host is a powerful, open technology for scripting and automation One of the ways that you may want to extend your scripts is by integrating them with a database Doing so really opens up the possibilities for your scripts Imagine, for example, a user login script that retrieves information about a user from a centralized database Conceivably, the user’s entire desktop could be reconfigured using the settings from the database! Or you could develop reporting scripts that extract information to the user’s local machine Those are some basic examples After you’ve read this chapter, you’ll no doubt be able to think of situations where you may be able to apply database access.à à à à à à à à To access databases, you’ll use the Microsoft Active Data Objects (ADO) ADO is Microsoft’s new standard for a database object model, and it’s typically used for data à access through Active Server Pages In this chapter, you’ll get a full introduction to ADO.à à à à On the 16th day of your introduction to WSH, you’llà à •Ãà Get an introduction to databases and data access via ADỖ à •Ãà See a reference for the ADO objectsà à à Ãà à à Ãà à à Ãà à •Ãà View examples that illustrate the use of the ADO objects from WSH scriptsà à à Introduction to Database Accessà à In this chapter, you'll learn how you can access RDBMS systems from your WSH scripts using the Microsoft ADO technology First the chapter discusses the history of data access; that will put ADO in context and help you to understand how it relates to earlier data access technologies such as ODBC, DAO, and RDO After that the chapter delves into the details of ADO with plenty of examples that will show you how you can use it with your WSH scripts.à à Persistent data storage is one of the most important requirements for literally any system Systems that require users to log in must somehow store information about a user's login ID and password Transaction systems must record and store information about, for example, customer orders Financial analysis systems may store information about historical and current stock prices Those are some basic examples—there are many others.à à In the past, numerous approaches have been taken to support persistent data storage In the old days, data for an application may have been stored in a simple flat file— sometimes just a basic text file That's essentially the approach taken by legacy systems that use ISAM files The limitations of flat text files are manifold; they have no abstraction to support complex analysis and aggregation of information stored in records Soon people began to create database systems that supported more robust record creation, deletion, and modification, as well as searching and other advanced functions Today, Relational Database Management Systems, or RDBMSs, have become popular Some examples of common RDBMSs include Oracle, Microsoft SQL Server, IBM DB2, and Sybase Adaptive Server.à à à à à à à à à à à à RDBMSs store information in tables Each table is structured as a set of rows and columns The columns represent individual fields, whereas the rows represent individual à data records, which areand Split Unregistered Version - http://www.simpopdf.com Simpo PDF Merge comprised of multiple columns RDBMSs allow you to create relationships between information stored in different tables This allows you, for example, to store information about a customer once and relate that information to any number of orders Because the customer information is stored once, it only needs to be updated once.à à à à With RDBMS systems, it can be complex to store objects developed using objectoriented languages such as C++ or Java in relational tables That’s because the concepts underlying object design are pretty different from the concepts for relational tables Consequently, object-oriented database management systems, or OODBMSes, have been gaining popularity Rather than using table concepts, OODBMSes support the storage of information as objects, so the mapping from objects implemented in object-oriented languages such as C++ or Java to data storage is greatly simplified There also hybrids such as object-relational systems that make it easier to store objects within RDBMSs by providing the logic to take object representations and break them down into relational table representations.à à For this chapter’s purposes, you’re going to look at ways that you can access RDBMS systems You’ll start with a look at SQL and ODBC, and then you’ll look at some of Microsoft’s early object models for data access, and finally you’ll examine the latest technology for database access, Microsoft Active Data Objects (ADO), and see how you can use it in your WSH scripts.à à ODBC and SQLà à In the early days, every database vendor had its own unique interface to its database system To use a particular vendor’s database, you needed to write code that used its function libraries and its specific syntax The situation was improved by the advent of a standard language for database access—the Structured Query Language, or SQL.à à SQL uses text statements to perform database functions Using SQL, you can add information to tables in a database, retrieve data from tables, combine and aggregate information from several tables, delete or change information, and change the structure of database tables For example, if you had a database of books, you might retrieve a list of authors by selecting information from a table of authors using syntax such as SELECT * FROM Authors The syntax of SQL is standardized by ANSI, and it's become the most common language to interface with RDBMSs.à à A further improvement was developed by Microsoft—Open Database Connectivity, or ODBC ODBC specifies an interface between applications and database engines Applications can use ODBC to pass SQL strings to databases and to retrieve information without requiring code specific to an individual database vendor's API ODBC serves as an abstraction layer between the application and the database For a database to be used through ODBC, you must have an ODBC driver for the database The ODBC driver translates between the standard ODBC API used by applications and the specific API provided by a database vendor The ODBC architecture is illustrated in Figure 16.1.à à à à à à à à à à à à à à à à à à à à à à à à Ãà Figure 16.1: The ODBC Architecture; a unified interface to RDBMS systems.à à à à From anPDF Merge and Split Unregistered the advantage of insulating you from Simpo application perspective, using ODBC has Version - http://www.simpopdf.com vendor-specific details It’s become the standard for database access for the Windows platform There are some problems with ODBC, however ODBC is based on Clanguage coding conventions Consequently, it can be difficult to use from objectoriented languages such as C++ or Visual Basic Microsoft’s solution to this issue has à been to provide object models that sit on top of ODBC and/or other database technologies The first object model was Data Access Objects (DAO), next came Remote Date Objects (RDO), and finally we have ADO In the next few sections, we’ll discuss each, then we’ll dive into ADO details.à à à à Microsoft DAO and RDOà à Microsoft’s first object model for database access was Data Access Objects, or DAO DAO was based on the Microsoft Jet database engine, which is the same database engine used by the Microsoft Access database, at least up to Access 97 Later versions of Access use an engine that’s similar to the engine in Microsoft SQL Sever DAO provides easy access to Microsoft Access databases and also to RDBMS databases through ODBC support that’s built into the Jet engine The object model for DAO is illustrated in Figure 16.2.à à à à à à à à à à à à Figure 16.2: The DAO object model.à à Ãà à à à DAO became popular with Visual Basic as the standard data access mechanism for version 3.0 of that language However, certain problems with DAO began to materialize First, the DAO object model is complex and relatively "heavy." To retrieve information from a database, you need to instantiate multiple DAO objects, a process that is both memory intensive and tedious Second, DAO provides slow access to ODBC databases For organizations that were using VB to access RDBMS systems through DAO’s ODBC support, the speed, or lack thereof, was a common problem.à à Microsoft’s solution to the speed problem was the Remote Data Objects, or RDO RDO was no longer based on the Microsoft Jet Database engine It was intended to be a more efficient, less memory-intensive object interface to ODBC databases It is much faster than using DAO to access ODBC databases but, as you can see from the illustration of the RDO object model in Figure 16.3, it’s still chock-full of objects.à à à à à Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com à à à à à à Figure 16.3: The RDO object model.à à Ãà à à à Because of the complexity of their object models, neither DAO nor RDO was particularly great for use in lightweight environments such as Active Server Pages (ASP) So Microsoft created a new object model, the Active Data Objects, or ADO.à à Microsoft ADOà à Microsoft ADO is the latest data access object model from Microsoft It’s a high-speed, efficient, and easy-to-use object-oriented framework for database access ADO allows you to manipulate data in databases that are exposed through the OLE DB standard OLE DB is an object standard for database access that supersedes the ODBC standard To access a database through OLE DB, it must have an OLE DB provider Conceptually, the OLE DB provider performs a similar function to an ODBC database driver.à à à à à à à à à à à Because many databases already provide ODBC drivers, Microsoft includes the Microsoft ODBC Provider for OLE DB The Microsoft ODBC Provider allows ADO objects to access ODBC databases through OLE DB, so you can use any database with ODBC support through ADO immediately Because it has an open model with standard interfaces implemented through providers, one of the major benefits of OLE DB is that it à can be used both with relational and non-relational data sources For our discussion, we’re going to focus on the practical issue of using the ADO objects for data access in WSH scripts, but if you want more information about OLE DB, refer to the Microsoft Web site at www.microsoft.com.à à à à à à Microsoft ADO also includes a capability called the Remote Data Service (RDS) RDS enables you to data remoting With data remoting, you move data from the server to the client in one step Any data manipulation is done on the client, and updates are returned to the server in a single round trip RDS can be used for Web applications to transfer data dynamically to and from a Web page for remote data access applications We won’t cover the RDS capabilities in this chapter, so if you want more details, refer to Microsoft ADO documentation.à The Microsoft Active Data Objects (ADO)à à The Microsoft Active Data Objects can allow you to easily integrate your WSH scripts with database systems Take a quick look at the ADO object model depicted in Figure 16.4 That’s the object model that you’ll be working with to access databases.à à à à à Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com à à à à à à Figure 16.4: The ADO object model.à à Ãà à Ãà à Noteà The diagram doesn’t show the Properties collection associated with the Connection, Command, Recordset, and Field objects The Properties collection can be used to attach dynamic attributes to the aforementioned ADO objects using à Property objects You can use all the other ADO objects without ever using the Property or Properties objects Specific database providers may use the Properties to expose special capabilities.à à à à à ADO has a simple object model, and there are few dependecies between objects If you want to quickly retrieve data or change data, you may only need to use the Recordset object! The Recordset is the object that you’ll use most frequently because it represents a database result set A result set is a sequence of records retrieved from a database It may be the result of the execution of a SQL command, it may be the contents of a database table, or it may be the results of the execution of a database stored procedure You can use Recordset objects to retrieve, add, or modify database information.à à à Ãà à Noteà For those of you who are unfamiliar with stored procedures, a stored procedure is essentially a compiled set of SQL commands Ãstored on a database server You can access a stored procedure using a syntax similar to a function call that you might make using VBScript.à à à à à All Recordsets use a database connection To establish a connection, you use a connection string Recordsets may either use a connection string directly or an instance of a Connection object that you pre-prepare using a connection string; in either case, ADO ensures that the Recordset is associated with a Connection object The connection string specifies all the details that are necessary to connect to a database It typically includes the provider, or driver, that should be used, the name of the database server and database, and the username and password to use when connecting We’ll cover connection strings in more detail in the documentation for the Connection.ConnectionString property later in the chapter.à à à à In addition to using it to connect to databases, you can use the Connection object to change data in databases using transactions A transaction allows you to treat several database changes as a unit of work This may be useful, à ... obtain references to individual Window objects by indexing the Windows collection or by using the ActiveWindow property The following code displays the caption of the first window in the Windows. .. "state", "Showing"à merlin.Get "state", "Speaking"à merlin.MoveTo 10, 10à merlin.Showà merlin.Get "state", "Moving"à merlin.MoveTo 2 57, 177 à merlin.Speak ("Isn’t it about time you started doing some... collection of Window objects representing open windows in the current Word application session You obtain references to individual Window objects by à indexing the Windows collection or by using the

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

Tài liệu cùng người dùng

Tài liệu liên quan