sams teach Yourself windows Script Host in 21 Days phần 3 pps

51 318 0
sams teach Yourself windows Script Host in 21 Days phần 3 pps

Đ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

The word file in this example is arbitrary and could be anything. This is often used when a collection object doesn’t support an absolute reference to the items within it: ObjFiles(1).name This is used most often with objects that contain a collection of items such as the File System Object or an Outlook Folder/Item Collection. You can exit the For Each loop at any time with the Exit For statement. Do Loop The Do Loop executes a statement repeatedly until a condition is true or while a condition is true. The While or Until condition can be set with the Do or Loop command, but you normally see it used in conjunction with the Do command: Do Until count = 5 count = count + 1 Loop Status = True Do While Status = True count = count + 1 If count = 10 Then Statue = False End If Loop You can use this method if you are testing each value with a function and want to find the first value that meets a certain condition. While Wend This is similar to the Do Loop, except the condition is not checked until the code gets to the Wend statement. If the condition is not met, execution starts over from the While statement: While count <10 count = count + 1 msgbox count Wend This method of looping is not very common. VBScript Functions There are a large number of functions provided by VBScript. They assist with conversions, string manipulation, formatting expressions, date/time functions, mathematical functions, and user input/output. In this section, you will look at examples of the more common functions that you are Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com likely to use in WSH scripts. Conversions Probably the most commonly used conversion function is Chr(), which returns the character for a given ANSI character code. The ANSI code for printable characters starts at 33. An example of using the Chr() function follows: for i= 65 to 75 strMsg = strMsg & i & " = " & chr(i) & vbLF Next Wscript.echo strMsg Because VBScript stores expressions automatically in the most suitable variant subtype, you might need to pass a variable to a function or COM object as a known type. These are some of the common conversion types: • Cdate(strDate) converts a recognizable date string to a date. An example of when you would use this is when your source date is in a long format and you want to add x days to it. • Cint(number) removes any decimal point value and returns an Integer. For example: strBirthDate = "September 20, 1962" Wscript.echo "I am " & Cint((Date – Cdate(strBirthDate)) / 365) & " years old" In the preceding example, Cdate(strBirthDate) returns 20/09/62. This is based on my OS system local settings. Subtracting this from today’s date results in 13283 days. Dividing this by 365 gives 36.3917808219178 years (approximately). Finally, Cint returns 36. If you experience type mismatch errors, you will probably need to use one of the conversion functions to solve the problem. If you want to find out how VBScript is storing your variable, there is a VarType function, which returns an Integer indicating the variant sub type: IType = VarType(veriable) Select Case Itype Case 0 ' Empty Case 1 ' Null Case 2 ' Integer Case 3 ' Long Integer Case 4 ' Single-precision floating-point number Case 5 ' Double-precision floating-point number Case 6 ' Currency Case 7 ' Date Case 8 ' String Case 9 ' Object Case 17 ' Byte Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com End Select There is also a simple test you can perform to detect if a variable is a number or text. IsNumeric() returns true if the variable or expression can be evaluated as a number. String Manipulation If you were to tell a programmer that VBScript can do cool things with strings, they would laugh and tell you to look at Perl because it has regular expression support. If you have ever seen one of those expressions, it probably didn’t make any sense at first, and fortunately, this is the VBScript chapter so I don’t have to explain it to you. VBScript has enough string manipulation functions to perform fairly complicated manipulations. You will cover these functions: • Instr Returns the position of the first occurrence of one string within another • InstrRev Returns the position from the end of the string where the required string is found • Len Returns the number of characters in a string • Ucase Returns a string that has been converted to uppercase • Left Returns a specified number of characters from the left side of a string • Mid Returns a specified number of characters from a string • Right Returns a specified number of characters from the right side of a string • Replace Replaces part of a string with another string The in string function is useful for checking that a string contains a required sub string or for finding the starting position for one of the other string functions. The syntax for this function is as follows: InStr([start, ]string1, string2[, compare]) The square brackets ([]) indicate optional values. An example is checking to see if an entered Internet email address is valid. If the @ symbol is not found in the string, the function returns 0. If there is an @, you check that there is at least one dot in the domain name as follows: strAddress = InputBox ("Please enter e-mail address") iATposition = Instr(StrAddress,"@") If iATposition <> 0 Then If Instr(iATposition, strAddress, ".") <> 0 Then Wscript.Echo strAddress & " is a valid address" Else Wscript.Echo "Invalid domain in " & strAddress End If Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Else Wscript.Echo "Internet address must contain an @ symbol" End If You will notice that the second If statement started looking for the dot character after the @ symbol because it is valid to have a dot in the username. Note that this is not an exhaustive test of valid Internet email addresses. The Left and Right functions are useful for returning parts of a string. For example, to get the extension of a filename, use the following: path = Right(path, InstrRev(path, ".")) To get the path of a UNC filename, use this: path = Left(path, InstrRev(path, "\")) To find the filename without an extension requires removing the drive/path prefix and extension, which can be done with the Mid function: FileStart = InstrRev(path, "\") FileLength = InstrRev(path, ".") - InstrRev(path, "\") FileName = Mid(path, FileStart, FileLength) This can also be done with one line: FileName = Mid(path, InstrRev(path, "\"), InstrRev(path, ".") - InstrRev(path, "\")) Probably the most powerful string function is Replace. The full syntax is as follows: Replace(expression, find, replacewith[, start[, count[, compare]]]) To demonstrate how useful this function is, imagine you have to convert a UNC path name to a URL. Assuming you have removed the Drive: and added http:// to the string, here is how you change the \ to / for every occurrence of the backslash. URL = Replace(path, "\", "/", 1, -1) By setting the count argument to -1, the function replaces all occurrences of the backslash. Object Assignment This is one of the more complex features that you will use extensively in scripts. The Set command assigns an object reference to a variable. An object in this case is a Component Object Model (COM) compliant DLL (or OCX) or a program that supports OLE automation, such as the Microsoft Office suite of applications. Wscript is a COM object that exposes practical functions for you to use. These functions have what are called methods and properties, which you can access (or automate) after you have assigned your own variable to the object you want to automate: Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Set WshNetwork = Wscript.CreateObject("Wscript.WshNetwork") Note OLE and COM are covered further in Chapter 14, "Overview of WSH and Application Scripting Capabilities." Error Handling There are two ways of dealing with errors in VBScript. You can either ignore them, which will cause your script to terminate and display an error message when an error is encountered, or you can use the On Error statement. Placing On Error Resume Next in your script will result in any line causing a runtime error to be skipped and execution to continue on the next line. This can cause the next line to produce unexpected results, so you need to check the Err object at critical places in your script to see if there has been an error. Err.Number is 0 if there has not been an error. If Err.Number is not 0, Err.Description might contain a useful description of the error for display or logging purposes. Here is an example that shows how to trap any problems with opening a file: On Error Resume Next Const ForReading = 1 Set objFS = CreateObject("Scripting.FileSystemObject") Set ts = objFS.OpenTextFile("c:\testfile.txt", ForReading) If Err.Number <> 0 Then Wscript.Echo "Error: " & Err.Number & "-" & Err.Description Else ’ Main code here End If If c:\testfile.txt does not exist, you get the following message: Error: 53-File Not Found If you want to trap an error for logging but also want to continue with the rest of the script, you can reset the error object with the following command: Err.Clear Note See Chapter 8, "Testing and Debugging WSH Scripts," for more information on debugging scripts. Script Design Now you are ready to start writing your own scripts, but try to remember a few good coding habits: • Use plenty of comments in your code. • Indent logical sections of code. • Place repeated code into a function or subroutine. • Use naming conventions. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com You can consider a task to be sequential, starting at the top and ending at the bottom, or you can think of it as modular. For simple scripts, the sequential method is okay, but for more complicated scripts, you will want to design reusable pieces of code that you can call when required. Consider this skeleton script design: ’ My Script Template ’ ’ Global Variables ’ Option Explicit Dim x, y, z ’ ’ Create Global Objects ’ Set WshShell = Wscript.CreateObject("Wscript.Shell") ’ Call Main() ’ Wscript.Quit ’ ’ ’ Subroutine: Main ’ Sub Main() ’Perform main program loop Mode = CheckParams(option) Select Case Mode Case 1 Call library1() Case 2 Call library2() End Select End Sub ’ Sub library1() End Sub ’ Sub library2 End Sub ’ Function CheckParams(TestOption) Dim CheckParams CheckParams = 1 End Function ’ End of File I will now describe the two main elements of this skeleton script: Sub procedures and functions. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Sub Procedures A Sub procedure performs some actions but does not return any results. You can pass arguments to the Sub procedure by placing the constants, variables, and expressions in the parentheses on the call. Call LogError("Failed to open file") Sub LogError(description) objLogFile.WriteLine "Error: " & description If DebugInteractive = True Then Wscript.Echo "Error: " & description End If End Sub You can also call a function without the Call statement: LogError "Failed to open file" You can pass a value, variable, or reference to an object to the subroutine or function. When passing a global variable to a function, you might want to ensure that the value cannot be changed by the code in the function. You can do this with the ByValue argument: Sub GetGroup(ByVal strUser) The default is ByRef, which means that a pointer to the storage location of the variable is passed to the subroutine or function. You can also pass multiple values by separating them with a comma. You must place them in the order that the subroutine expects to use them: Call LogError("Failed to open file", Wscript.ScriptName) . . Sub LogError(description, file) objLogFile.WriteLine "Error in " &_ file & ": " & description If DebugInteractive = True Then Wscript.Echo "Error: " & description End If End Sub Functions A function is similar to a Sub procedure except that it can return a result: Wscript.Echo "I am " & GetYears("20/09/62") & " years old" . . Function GetYears(birthDate) GetYears = Cint((Date – BirthDate) / 365) End Function Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com The value returned is passed in the variable, which must be named the same as the function name. Variables used in a Sub or function that have not been dimensioned at the top level of the script are local to that section of code. Error trapping must also be defined for each subroutine or function if required because the On Error statement is local to the script level in which it is invoked. Naming Conventions Everyone likes standards, and they will help the maintainability of your code. Remember that someone else might have to figure out how your code works in the future. I have taken some of the relevant conventions for constants and variables from the Microsoft guidelines and presented them in Table 5.1. Table 5.1 Conventions for Constants and Variables Subtype Prefix Example Byte byt bytDTR Date (time) dtm dtmStartFinYear Error err errStdMsg Integer int intQuantity Object obj objExcel String str strUserName Common VBScript Usage Scenarios In this section you will look at some sample scripts that assist with tasks that can be quickly performed and save you time. Reading an IIS Log File and Counting a Type of Request Your boss has asked you to report on how many times the company profile has been downloaded from your Web site. You start looking inside the IIS log file with notepad using the find function. You say to yourself, "This is hopeless, there must be a better way," and you are right. You decide to use WSH with the file system object and some VBScript string functions. This is what you come up with: ’ FILE: VBSlogrpt.vbs ’ AUTH: Ian Morrish ’ DESC: search all log files for a string and output to a report Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com file the number of ’ matches per day ’ On Error Resume Next ’ ’ Define Constants ’ Const Log_File_Path = "c:\winnt\system32\logs\" Const Log_File_Extension = ".LOG" Const Report_File = "C:\temp\report.csv" Const Search_String = "Component.asp" Const ForWriting = 2 ’ Dim strFileName, strLine, strLogDate Dim iCount ’ ’ Get directory object ’ set objFS1 = Wscript.CreateObject ("Scripting.FileSystemObject") Set objLogFolder = objFS1.GetFolder(Log_File_Path) If Err.Number <> 0 Then Wscript.Echo "Logfile path not found" Wscript.Quit End If ’ ’ Open report file ’ set objFS2 = Wscript.CreateObject ("Scripting.FileSystemObject") Set objReport = objFS2.OpenTextFile(Report_File, ForWriting, True) If Err.Number <> 0 Then Wscript.Echo "Error creating report file" Wscript.Quit End If objReport.WriteLine "Date,Downloads" ’ ’ Check logfiles for valid name ’ Set objFiles = objLogFolder.Files For each file in objFiles ’ ’ Get the file name and see if the extension is correct ’ there may be other file types in this directory strFileName = Ucase(file.Name) ’ Next line is for debugging & shows when we forget the ’ trailing \ on the logfile extension constant ’ Wscript.Echo Log_File_Path & strFileName If Instr(strFileName, Log_File_Extension) <> 0 Then ’We have a log file, open it. set objFileContents = objFS1.OpenTextFile (Log _ File _ Path Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com & strFileName) If Err.Number <> 0 Then ’File might be in use by IIS so skip it Wscript.Echo "Can’t open file" & strFileName Exit For End If ’ ’ Reset counter for each day ’ iCount = 0 ’ ’3rd line contains date eg #Date: 1999-01-29 00:31:21 ’ Use the Instr and Mid functions to get the year-month- date ’ objFileContents.ReadLine objFileContents.ReadLine strLogDate = objFileContents.ReadLine strLogDate = Mid(strLogDate, Instr(strLogDate, " ") + 1, 10) ’ ’ Now read in each line looging for the file name ’ do while objFileContents.AtEndOfStream <> True strLine = objFileContents.ReadLine If Instr(strLine, Search_String) <> 0 Then iCount = iCount + 1 End If Loop ’ ’ Write daily download count to report file ’ objReport.WriteLine strLogDate & "," & iCount End If Next ’file Now you can use Excel to quickly produce a trend graph, and your boss is happy. Using Command-Line Arguments WSH provides the capability to access the command-line arguments that might be present when the script is run. The following script is a skeleton that you can use in your own application: ’ FILE: VBSparams.vbs ’ AUTH: Ian Morrish ’ DESC: Extract command line parameters ’ matches per day ’ On Error Resume Next Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... the VBScript scripting language and how it is used to create scripts that run under the Windows Scripting Host Today you’ll learn about JScript, the other scripting language supported by WSH The JScript scripting language is based on the popular Java programming language JScript is functionally equivalent to VBScript, which means that you can write scripts in JScript that perform the same tasks as scripts... strings together.à à Commentsà à You can include notes and descriptions in JScript code by using comments, which help to explain how a section of code works There are two types of comments supported by JScript: single-line and multiline A single-line comment begins with a pair of forward slashes (//) and indicates that the remainder of the line is a comment Following is an example of a single-line... environment (used in a login script, for example).à à à à à Running Scripts Using CSCRIPTà à CSCRIPT is one controller of ActiveX scripting engines provided by Microsoft It operates in a command prompt (or MS-DOS prompt) environment This provides an excellent mechanism to perform lightweight, noninteractive scripting tasks such as login scripting, frequent administrative tasks, and so on.à à The CSCRIPT application... http://msdn.microsoft.com/scripting/ default.htm?/scripting/windowshost/ Windows 2000 will provide integrated support for WSH.à à à à Running Scripts the Old Wayà à Unlike scripting implementations within Internet Explorer and IIS, WSH scripts do not have to be embedded between delimiters or "tags" in order for them to function To better understand the differences, you will look at the same script embedded in the three... the various scripting languages supported by the Windows operating system You will learn how to execute scripts using the two available "nonWeb" applications supplied by Microsoft: cscript.exe and wscript.exe You will also examine how file associations can link your scripts to your favorite script engine and how script execution can be controlled using WSH files Finally, you will examine the integrated... create JScript scripts that run under WSHà à à Introduction to JScriptà à JScript is Microsoft's implementation of the JavaScript scripting language that was originally developed by Netscape Communications Although JScript is similar in many ways to JavaScript, JScript includes Microsoft extensions, a broader object model, and integration with Microsoft technologies Like VBScript, JScript is an interpreted,... Displaying Informationà à Displaying information to the user is a very common task in any scripting language, and JScript is no exception It’s easy to display information using the Echo() method defined in the WScript object Following is an example of how this method is used:à à WScript.Echo("Howdy!");à à You simply pass a string to the Echo() method, which in turn displays the string in a message box Figure... provide support for VBScript-based and JScriptbased scripts IE 3. 0 installs the scripting engines that will enable the scripts Ãto be interpreted by the operating system Although IE 3. 0 is the minimum requirement to enable VBScript and JScript support, I highly recommend that à Simpo you install the latest Split Unregistered Version - provides you with the PDF Merge and version of Internet Explorer This... time This is the default setting for wscript and cscript.à à //Logoà à à à à à à à à Defines the script timeout (in seconds) The default is no timeout This option can be used to prevent damage occurring à from scripts caught in an infinite loop Use of this option is recommended.à à Show the cscript command usage.à à à à à à à à Version 5.0 of cscript.exe is included in the Windows 95 and NT 4.0 distributions... LiveScript The end result was JavaScript, which used some elements of Java in the context of a scripting environment The main purpose of JavaScript was to provide Web developers with a means of injecting interactivity into Web pages without having to build full-blown Java applets.à à à à à à à à à à à à Ãà à Noteà Although Java and JavaScript are similar in terms of their syntax, they were Ãoriginally . OS system local settings. Subtracting this from today’s date results in 132 83 days. Dividing this by 36 5 gives 36 .39 1780 8219 178 years (approximately). Finally, Cint returns 36 . If you experience. string with another string The in string function is useful for checking that a string contains a required sub string or for finding the starting position for one of the other string functions. The. "Testing and Debugging WSH Scripts," for more information on debugging scripts. Script Design Now you are ready to start writing your own scripts, but try to remember a few good coding

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

Từ khóa liên quan

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

  • Đang cập nhật ...

Tài liệu liên quan