sams teach Yourself windows Script Host in 21 Days phần 5 docx

51 276 0
sams teach Yourself windows Script Host in 21 Days phần 5 docx

Đ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 à à à With batch files, there is no equivalent debugging capability There’s nothing built in to the operating system that enables you to debug them, and the Microsoft development tools don’t help you to debug them either.à à Support for Variablesà à WSH provides the capability for you to create and manipulate variables within your scripts Unlike batch files, variables are constrained so they are only available within a single script during the execution of the script This is a big advantage over batch files, which are restricted to using shared environment variables, because it eliminates potential conflicts that can occur between scripts Furthermore, variables within WSH scripts can take any type of value including strings, numbers, and objects In batch files, environment variables are always strings.à à à à à à à à à à Comparing Batch File Usage With WSHà à If you’ve used batch files before, you might wonder how you can translate your batch files into their WSH equivalent so that you can take advantage of the enhanced capabilities of WSH In this section, you’ll take a look at batch files in comparison to WSH features.à à à à à à Ãà à Noteà As you go through this section, you’ll notice that some of the WSH equivalents for batch file functions are much longer in terms of Ãlines of code That’s one of the few advantages of batch files over WSH scripts You might find that for certain tasks it’s easier for you to implement batch files.à à à à à Batch Language and WSH Equivalentsà à First, you’re going to take a look at some of the language constructs that are used in batch files and the equivalent language constructs in WSH It’s important to keep in mind that these language constructs are dependent on the WSH scripting language that you decide to use.à à Using Variablesà à If you want to use variables in batch programs, you must use environment variables Here’s an example that shows how you might use environment variables in a batch program:à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à Rem Create an environment variable and set its valueà Rem to the string ’Happy Holidays’à Set MY_VAR=Happy Holidaysà à Rem Here’s where we would perform additional actions à à Rem At the end of the script, we need to set the variableà Rem to a blank string to cleanup the environment If weà Rem don’t so, the command environment may containà Rem lots of junk.à Set MY_VAR=à à à à à à à à à à à à à à When you’re using scripts with WSH, you don’t needVersion - http://www.simpopdf.com Simpo PDF Merge and Split Unregistered to use environment variables That’s much safer, and you don’t need to clean up the variables at à the end of your WSH script Here’s a short example that shows how you can use VBScript to create a variable:à à à à à à à à à à à à ’ Allocate a variable, then set its valueà Dim my_varà my_var = "Happy Holidays"à à à à à à ’ NOTE: we don’t need to cleanup the variableà à Here’s how you the same type of thing using JScript:à à ’ Allocate a variable, and set its valueà var my_var = "Happy Holidays";à à à à à à à à à à à à à à As you can see, the JScript code is actually somewhat shorter than the VBScript equivalent In any case, like VBScript, you don’t need to clean up the variable after you use it.à à One thing that you can with variables in WSH scripts is set them to values that are more than just strings The following example shows how you can use VBScript to set variables that are numbers and objects:à à à à à à à à à à à à à à à à à à à à à à ’ First allocate a variable to hold a number, then set its valueà Dim numà num = 12à à ’ Next, allocate a variable to hold an object, then create anà ’ object instanceà Dim fileobjectà Set fileobject = Wscript.CreateObject("Scripting.FileSystemObject")à à à à à à à à à à à à When you use WSH variables, you have very few limitations You also don’t need to worry about collisions between variables that you use and variables that exist in other scripts.à à Implementing Conditions and Logicà à Batch programs use the IF statement in conjunction with GOTO statements to evaluate logical conditions and branch accordingly Here’s a batch file example that checks a condition:à à à à à à à à à à à à à à à à à à à à à Rem Create a variable to illustrate the use of the IF statementà Set MY_VAR=ValueAà à Rem Now check the variable using IF - if the value of the variable isà Rem the string ’ValueA’, the script will go to the label WasValueAà Rem and continue executionà à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à IF %MY_VAR%.==.ValueA GOTO WasValueAÃVersion Simpo PDF Merge and Split Unregistered à - http://www.simpopdf.com à Rem This is the equivalent of the else clauseà Echo MY_VAR was not ValueAà Goto BatchEndà à :WasValueAà Echo MY_VAR was ValueAà à Rem We’ll just fall through to the end of the batch sequence à à :BatchEndà Rem This is the end of the batch sequence, so we’ll cleanupà Rem the variable that we used.à Set MY_VAR=à à à à à à à à à à à à à à à à à à That works okay when you have a simple condition If you have a more complex condition, batch files quickly become messy The following example is very similar to the first but includes a more complex condition:à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à Rem Create a variable to illustrate the use of the IF statementà Set MY_VAR=ValueBà à Rem this time, we’ll check for ValueA, ValueB, or otherà IF %MY_VAR%.==.ValueA GOTO WasValueAà IF %MY_VAR%.==.ValueB GOTO WasValueBà à Rem This is the equivalent of the last else clauseà Echo MY_VAR was not ValueA or ValueBà Goto BatchEndà à :WasValueAà Echo MY_VAR was ValueAà Goto BatchEndà à :WasValueBà Echo MY_VAR was ValueBà à Rem Fall through à à :BatchEndà Rem This is the end of the batch sequence, so we’ll cleanupà Rem the variable that we used.à Set MY_VAR=à à à à à à à à à à à à à à à à à à à à à à à à à à à à à Now, take a look at the WSH script equivalents For the first simple case you can use the following VBScript:à à à à à à à à à à à à à à à à à à à à à à à à ’Simpo PDFvariable toSplit Unregistered Versionuse ofà Create a Merge and use to illustrate the - http://www.simpopdf.com à ’ the If Then statementà à Dim my_varà à my_var = "ValueA"à à à ’ Now we use If Then to evaluate our program’s logicà If my_var = "ValueA" Thenà Wscript.Echo "my_var was ValueA"à Elseà Wscript.Echo "my_var was not ValueA"à End Ifà à à à à à à à à à à To the same thing using JScript, you can use the following, which uses slightly different syntax but is conceptually identical:à à à à à à à à à à à à à à à à à à à à à // Create a variable to use to illustrate the use of the if statementà var my_var = "ValueA";à à // Now we use if to evaluate our program’s logicà if (my_var == "ValueA") {à WScript.echo("my_var was ValueA");à } else {à WScript.echo("my_var was not ValueA");à }à à à à à à à à à à à à à The advantage of the two examples is that the flow of the program is simple and easy to understand; the flow is certainly simpler and easier than the flow of the batch file With the second batch file example, you can quickly see how code turns into spaghetti code that can be very difficult to debug and maintain Now, take a look at the equivalent of the second batch file in VBScript:à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à ’ Create a variable to use to illustrate logical branchingà Dim my_varà my_var = "ValueB"à à ’ Now we use If Then ElseIf to evaluate our program’s logicà If my_var = "ValueA" Thenà Wscript.Echo "my_var was ValueA"à ElseIf my_var = "ValueB" Thenà Wscript.Echo "my_var was ValueB"à Elseà Wscript.Echo "my_var was not ValueA"à End Ifà à ’ And here’s a cleaner alternative using the SELECT CASE statementà ’ this version is easier to expand if you need to handle multipleà ’ simple casesà à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à Select Case Merge and Split Unregistered Version - http://www.simpopdf.com à Simpo PDF my_varà Case "ValueA"à à Wscript.Echo "my_var was ValueA"à à Case "ValueB"à à Wscript.Echo "my_var was ValueB"à à Case Elseà à Wscript.Echo "my_var was not ValueA or ValueB"à à End Selectà à à à à That example demonstrates two different ways that you can perform branching logic in VBScript Now take a look at similar functionality using JScript:à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à // Create a variable to use to illustrate logical branchingà var my_var = "ValueB";à à // Now we use if else to evaluate our program’s logicà if (my_var == "ValueA") {à WScript.echo("my_var was ValueA");à } else if (my_var == "ValueB") {à WScript.echo("my_var was ValueB");à } else {à WScript.echo("my_var was not ValueA");à }à à // And here’s a cleaner alternative using the SELECT CASE statementà // this version is easier to expand if you need to handle multipleà // simple casesà switch (my_var) {à case "ValueA":à WScript.echo("my_var was ValueA");à break;à case "ValueB":à WScript.echo("my_var was ValueB");à break;à default:à WScript.echo("my_var was not ValueA or ValueB");à }à à à à à à à à à à à à à à à à à à à à à à à à à à à à à You can see that the JScript example is very similar to the VBScript example; the syntax varies a little Both examples are much better structured than the batch file example If you need to use complex logic, consider changing your batch files to WSH scripts so that you can make use of the more powerful, simpler language features.à à Performing Iterationà à à à à à In batch files there are two basic types of iteration; you can iterate over a group of files using the FOR command, or you can perform standard, plain- à vanilla iteration using theand Split Unregistered Version - http://www.simpopdf.com Simpo PDF Merge GOTO statement The second type of iteration is similar to the typical iteration that’s used in a program for a while or for type of loop, but unfortunately it’s much weaker.à à à à Here’s an example that illustrates the FOR command in a batch file:à à @Echo Offà for %%f in (c:\winnt\system32\e*.dll) echo %%fà à à à à à à à à à à If you run a batch file that contains the preceding commands, you see the results shown in Figure 10.5.à à à à à à à à Figure 10.5: Results of running the for iteration example.à à à Ãà à à à Typical batch files use GOTO in conjunction with IF statements to perform conditional iteration Here’s an example from gotoloop.bat that shows that type of iteration:à à @Echo Offà à à à à à à à à à à à à à à à à à à à à à à à à à à :BeginLoopà Echo %1à Shiftà à If %1.== Goto :ExitLoopà Goto BeginLoopà à :ExitLoopà Echo Done!à à à à à à à à à à à à à The previous example shows a batch file loop that iterates through the parameters for the batch file If the batch file is run with the command line gotoloop IterationA IterationB IterationC IterationD, you see the results in Figure 10.6.à à Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com à à à à à Figure 10.6: Results of running the goto iteration example.à à à Ãà à à à The batch file iteration techniques are effective but very clunky They make it easy to iterate over multiple files but difficult to iterate for a specific number of times or until a complex condition is satisfied.à à à Ãà à Noteà Some of these batch file restrictions have been eliminated with Windows NT command extensions For example, the FOR à command is extended to perform iteration for a specific sequence The following code example illustrates the extended syntax:à à à for /L %%n in (1,1,10) echo %%nà à à à Ãà à The output from a batch file containing that FOR example is shown in Figure 10.7 There are also some additional enhancements with the command extensions that make it possible to simulate à subroutines using batch files The extensions are very useful; however, they are still not as flexible or anywhere near as powerful as WSH scripts.à à à Ãà à à à à à à à à à Ãà à Figure 10.7: Example showing extended for syntax.à à à embedded loops However, this is one situation where the WSHhttp://www.simpopdf.com Simpo PDF Merge and Split Unregistered Version - equivalent is not necessarily as simple or as short as the batch file version Iterating over a group of files can be more complex but also more flexible using WSH Here’s an example that uses VBScript to iterate over all the files in the Windows NT system directory:à à à à à à à à à à à à à à à à Dim fso, folder, fileà Set fso = Wscript.CreateObject("Scripting.FileSystemObject")à Set folder = fso.GetFolder("C:\WINNT\SYSTEM32")à à à à à à For Each file in folder.Filesà Wscript.Echo file.Nameà Nextà à That’s not too complex, but it gets worse If you want to iterate over just a specific type of file, like all the DLLs that begin with the letter e, you need to implement additional file-checking logic Here’s an example that does the check:à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à Dim fso, folder, file, nameà Set fso = Wscript.CreateObject("Scripting.FileSystemObject")à Set folder = fso.GetFolder("C:\WINNT\SYSTEM32")à à à à à à For Each file in folder.Filesà name = LCase(file.Name)à à à à à ’ First check first letter of file nameà If Left(name, 1) = "e" Thenà ’ Check file extensionà If fso.GetExtensionName(name) = "dll" Thenà Wscript.Echo nameà End Ifà End Ifà à à à à à à à Nextà à The output of the preceding example is depicted in Figure 10.8.à à à à à à à à à à à Figure Merge and over Unregistered Version - http://www.simpopdf.com à Simpo PDF10.8: Iterating Splitfiles using VBScript.à Ãà à à à Both of those examples show some of the excellent looping capabilities provided by WSH, but they also show that sometimes WSH scripts might not be as easy to implement as batch files Here’s another simple example that illustrates the use of the while loop:à à à à à à à à à à à à à à à à à Dim count, nameà count=1à Do While (count < 10) And (name "iteration5")à name = "iteration" & countà Wscript.Echo nameà count = count + 1à Loopà à à à à à à à à à à That’s obviously a very trivial example, but it does demonstrate complex logic and comparisons that are much better than the capabilities provided by batch files.à à Error Handlingà à With batch files, errors are captured using the IF ERRORLEVEL statement When a batch file runs a command, the command might return a numeric DOS error level Typically, an error level of zero represents success, whereas a nonzero error level is a failure number Here’s an example that shows the use of IF ERRORLEVEL:à à à à à à à à à à à à à à à à à à à à à à à à à à à à à @Echo Offà Type notafile.txtà If errorlevel Goto :ErrOccurredà Echo No error occurred.à Goto :EndBatchà à :ErrOccurredà Echo An error occurred with the type command!à à à à à à à à à à à :EndBatchà à Assuming that the notafile.txt file doesn’t exist, running the batch file produces the result shown in Figure 10.9 The Type command displays a text error and sets the DOS error level That’s more feedback than some other commands; many set the error level without displaying a descriptive message The IF ERRORLEVEL logic is also very weak because you can’t use it to check for a specific error level; it checks for an error equal to or greater than the error level that is specified.à à à à à Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com à à à à à Figure 10.9: A batch file that demonstrates error handling.à à à Ãà à Ãà à Noteà This is another situation where the Windows NT command extensions improve the batch file capabilities With the command Ãextensions, the syntax for IF enables you to check for a specific error level using the %errorlevel% variable and the EQU operator Here’s a short example of the extended syntax:à à à à à WSH scripts, assuming that you’re using VBScript, provide much more robust error handling than batch files (Unfortunately, the current version of JScript doesn’t provide error handling capabilities.) VBScript provides an Err object that provides properties that include a numeric error code, a description of the error that occurred, and the source of the error You can easily check for an error using logic that checks the Err.Number property Here’s an example that illustrates the check for an error:à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à ’ The following line must be included to set up VBScript errorà ’ handlingà On Error Resume Nextà à ’ We’ll use a loop that will attempt to get a set of files; theà ’ last one is bogus and will cause an error to occurà Dim filelist, filename, fso, fileà filelist = Array("user32.dll", "kernel32.dll", "not_a_dll.dll")à Set fso = Wscript.CreateObject("Scripting.FileSystemObject")à For Each filename In filelistà Wscript.Echo "Getting the file object for " & filename & " "à Set file = fso.GetFile("c:\winnt\system32\" & filename)à If Err.Number Thenà Wscript.Echo "Unable to get file; an error occurred."à Wscript.Echo "Err #" & Err.Number & ", " & Err.Descriptionà à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à ’à à Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com If tCopyFile Thenà à On Error Resume Nextà à filesys.CopyFile sMasterFile, sFileToCheck, Trueà à If Err.Number Thenà à ’à à ’ Error occurred during copyà à ’à à shell.Popup "Error: The copy failed, additional error " & à _à "information is listed below." & vbCrLf & vbCrLf & _à à "(" & Err.Number & ") " & Err.Description, 0, _à à "chkver.vbs", ICON_STOPà à Wscript.Quit Err.Numberà à Elseà à ’à à ’ Show success; notice that the time-out is setà à ’ so the message box will disappear after secondsà à ’ if user doesn’t click on it firstà à shell.Popup "The file " & sFileToCheck & " was " & _à à "successfully updated with " & sMasterFile, 5, _à à "chkver.vbs", ICON_INFOà à End Ifà à End Ifà à à à à The script takes two arguments; the first argument is the file that should be checked, and the second argument is the master file If the file to check is older or a different size than the master file, it is replaced by the master file Figure 11.9 shows the results after a file has been updated.à à à à à à à à à Figure 11.9: Message displayed to user after file is copied.à à Ãà à à à When the script runs, it first checks to ensure that neither of the file arguments contain a wildcard character If either contains a wildcard, the results of running the script could be unpredictable Next, the filenames are checked to ensure that they are the same To so, compare the names that are returned by the FileSystemObject.GetFileName() function GetFileName() returns just the filename from a file path.à à The script then checks to see whether the file that is being checked exists If the file doesn’t exist, you display a message to the user and set a flag indicating that you should copy the file If it does exist, you check it against the master file using the File.DateLastModified and File.Size properties If it is older or a different size than the master file, set the copy flag Finally, if the copy flag is set, you attempt to copy the file and then display an error or success message depending on the result.à à à à à à You’ll notice that we have used some additional arguments to the shell.Popup() method For the success message at the end of the script, we’ve added a timeout so that the message Merge and Split Unregistered Version - http://www.simpopdf.com Simpo PDFdisappears automatically after five seconds We’ve also added a title for the à message dialog and an icon The success message uses the information icon; the various error messages use the stop icon.à Program Registry Settingsà à à à à à On early versions of the Microsoft Windows platform, text files with the extension INI were typically used to store program settings That was a reasonable early solution but posed problems as programs began to share information and settings As a solution, Microsoft developed the Windows Registry to provide a central repository for program, user, and system settings.à à The Registry is a hierarchical data structure that is conceptually similar to a directory system To examine the Registry, you can use the Windows standard regedit program Figure 11.10 shows an example of the Windows Registry and program settings.à à à à à à à à à à à à Figure 11.10: The Windows Registry and program settings.à à Ãà à à à In the Registry, there are keys, subkeys, and values Several standard root keys are à used to navigate to program settings Two of the most commonly used are the following:à à Ãà à •Ãà HKEY_CURRENT_USER This is the root in the Registry for settings for the current user.à à à Ãà à •Ã HKEY_LOCAL_MACHINE This is the root in the Registry for settings for the current à machine.à à à Each Registry key can contain multiple values A value consists of a name and the actual value, which may be a string, a DWORD, a binary value, or something else Most modern Windows programs use the Registry to store their settings Windows itself uses the Registry à Ãto store settings for Windows components For example, the HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\ Advanced\Hidden Registry value is used to determine whether a user should see hidden files when she uses the Windows Explorer.à à à à à Many values are in the Registry It's worthwhile to look through the Registry to see what types of information are stored And, with WSH, you can alter Registry values and consequently change program settings Next, you're going to look at some functions you can perform with WSH and the Registry.à à à à à Reading the Registry and Checking Program Settingsà Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com à à à Reading the Registry from WSH is easy using the WshShell object WshShell provides the RegRead() method, which allows you to read the value of a Registry key or Registry value In Listing 11.8, you’ll see how you can use the RegRead() method.à à Listing 11.8 chkreg.js—Check Program Settings in the Registryà à // // // // // //à // à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à FILE: chkreg.jsà DESC: This script demonstrates how you can use VBScriptà to check for program registry settings.à AUTH: Thomas L Fredellà DATE: 12/9/1998à à à à à à Copyright 1998 Macmillan Publishingà à à à //à // "Constants"à //à // These are paths to registry keysà //à var EXPLORER_SHOW_HIDDEN =à "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\" +à "Explorer\\Advanced\\Hidden";à var CURRENT_WALLPAPER =à "HKCU\\Control Panel\\Desktop\\Wallpaper";à à //à // Instantiate a shell object; we’ll use theà // RegRead() methodà //à var shell = WScript.createObject("WScript.Shell");à à //à // Retrieve and display some registry valuesà //à var nHidden = shell.RegRead(EXPLORER_SHOW_HIDDEN);à var sWallpaper = shell.RegRead(CURRENT_WALLPAPER);à WScript.Echo("chkreg.js: The setting for explorer to show " +à "hidden files is " + nHidden + ".");à WScript.Echo("chkreg.js: The current wallpaper is ’" +à sWallpaper + "’.");à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à The chkreg.js is a simple example that reads and displays two Registry settings There’s not much to it It sets some constants that are the paths to Registry values, it instantiates a WshShell object, and finally it calls the WshShell.RegRead() method There are two important things to notice First, instead of specifying HKEY_CURRENT_USER as the root for the Registry settings, we’re using the abbreviation HKCU The WshShell.RegRead() method recognizes abbreviations for commonly used Registry roots Second, because this example uses JScript, the paths to the Registry keys must contain double-slashes because a single slash is an escape character (the same is not true for VBScript).à à à à à Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Changing Program Registry Settingsà à In Listing 11.9, you’ll see how you can change settings in the Registry.à à à à à à Cautionà Before you make any changes to the Registry, make sure that you back Ãup the Registry or create an emergency repair disk By changing settings in the Registry, you could cause Windows or other programs to fail.à Ãà à à à à à Listing 11.9 writereg.vbs—Change Program Settings in the Registryà à ’ ’ ’ ’ ’ ’à ’ à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à FILE: writereg.vbsà DESC: This script demonstrates how you can use VBScriptà to modify program registry settings.à AUTH: Thomas L Fredellà DATE: 12/9/1998à à à à à à Copyright 1998 Macmillan Publishingà à ’à ’ Constantsà ’à ’ These are paths to registry keysà ’à Const NOTEPAD_KEY = "HKCU\Software\Microsoft\Notepad\"à Const EXPLORER_KEY = _à à à à à à à à à à à "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\"à à On Error Resume Nextà à ’à ’ Instantiate a shell object; we’ll use it for RegWrite()à ’à Dim shellà Set shell = Wscript.CreateObject("WScript.Shell")à à ’à ’ First change value for Notepad’s fontà ’à shell.RegWrite NOTEPAD_KEY & "lfFaceName", "Courier New"à If Err.Number Thenà Wscript.Echo "An error occurred while changing notepad’s font."à Wscript.Echo "(" & Err.Number & ") " & Err.Descriptionà Wscript.Quit Err.Numberà End Ifà à ’à ’ Next change Explorer to hide hidden filesà ’à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à shell.RegWrite EXPLORER_KEY & "Hidden", 0, "REG_DWORD"à à Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com If Err.Number Thenà à Wscript.Echo "An error occurred while changing ’show " & _à à "hidden’ files in the explorer."à à Wscript.Echo "(" & Err.Number & ") " & Err.Descriptionà à Elseà à Wscript.Echo "writereg.vbs: Changed registry settings."à à Wscript.Echo ""à à End Ifà à Wscript.Quit Err.Numberà à à à à The preceding writereg.vbs script uses a structure similar to the chkreg.js script Begin with embedded constants for Registry paths, instantiate a WSH shell object, and then change Registry settings using the WshShell.RegWrite() method The two settings that you change are the font for the Windows Notepad program and the Show Hidden Files setting for the Windows Explorer.à à à à Administering User Shortcuts and Foldersà à The Windows Scripting Host provides powerful capabilities to programmatically administer Windows shortcuts and folders Using WSH, you can easily create or delete shortcuts and folders In the next few sections, you’ll look at WSH code that can be used to perform those functions.à à Managing Shortcutsà à Creating and deleting shortcuts is easy using WSH To create shortcuts, we’ll use the versatile WshShell object WshShell provides a method called CreateShortcut() to create new shortcut objects You can use that in conjunction with the WshShell.SpecialFolders property to create shortcuts on the Windows desktop and Start menu To delete shortcuts, use WshShell in conjunction with the FileSystemObject.à à The next few sections provide detailed code examples that illustrate some of the functions that you can perform with shortcuts using WSH.à à Checking for a Shortcutà à Listing 11.10 uses the WshShell object in conjunction with the FileSystemObject to check for the existence of a shortcut.à à Listing 11.10 chkscut.vbs—Check for Shortcutsà à ’ FILE: chkscut.vbsà ’ DESC: This script demonstrates how you can use VBScriptà ’ to create Windows shortcuts.à ’ AUTH: Thomas L Fredellà ’ DATE: 12/9/1998à ’à ’ Copyright 1998 Macmillan Publishingà à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com On Error Resume Nextà à ’à ’ Check arguments & show usage if necessaryà ’à If Wscript.Arguments.Count Thenà Wscript.Echo "USAGE: chkscut.vbs [shortcut file]"à Wscript.Echo ""à Wscript.Echo " This checks to see if the ’shortcut file’"à Wscript.Echo " exists."à Wscript.Echo ""à Wscript.Quit 1à End Ifà à Dim sLinkFileà Dim filesysà à ’à ’ We’ll accept file paths in the form \file.lnkà ’ so first we need to expand the folder & resolve toà ’ an absolute pathà ’à sLinkFile = ExpandFilePath(Wscript.Arguments(0))à Wscript.Echo "chkscut.vbs: Expanded path to link is ’" & _à sLinkFile & "’."à à ’à ’ Check to see if file exists using FileSystemObjectà ’à Set filesys = Wscript.CreateObject("Scripting.FileSystemObject")à If Not filesys.FileExists(sLinkFile) Thenà Wscript.Echo "chkscut.vbs: The shortcut link file doesn’t exist."à Elseà Wscript.Echo "chkscut.vbs: The shortcut link file exists."à End Ifà à ’ -à ’ FUNC: ExpandFilePath(sPath)à ’ DESC: Returns a string that represents the expandedà ’ file path.à ’ -à Function ExpandFilePath(sPath)à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à On PDF Resume Nextà à Simpo ErrorMerge and Split Unregistered Version - http://www.simpopdf.com à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à ’à ’ We need a shell object to expand special foldersà ’à Set shell = Wscript.CreateObject("WScript.Shell")à à à à à à Dim asPathSegments, iSeg, sSegà Dim sSpecialFolderà Dim shellà à à à ’à ’ First we’ll split the input path into an arrayà ’ of strings using ’\’ as a delimiter; this willà ’ make the search easy, because we’ll only have toà ’ iterate through an array, assuming the path isà ’ well-formedà ’à asPathSegments = Split(sPath, "\")à For iSeg = LBound(asPathSegments) To UBound(asPathSegments)à sSeg = asPathSegments(iSeg)à If Len(sSeg) > Thenà ’à ’ A special folder must be AT LEAST characters,à ’ but in reality will be more ala à ’à If (Left(sSeg, 1) = "") Thenà ’à ’ Attempt to expand this path segmentà ’à sSpecialFolder = Mid(sSeg, 2, Len(sSeg) - 2)à asPathSegments(iSeg) = shell.SpecialFolders (sSpecialFolder)à End Ifà End Ifà Nextà à ’à ’ Now we can re-assemble the path and return ità ’à ExpandFilePath = Join(asPathSegments, "\")à End Functionà à The script begins with a basic check to ensure that the command-line parameters are specified correctly Next, we call an interesting function that we’ve developed called ExpandFilePath(), which takes the input argument and scans it for special embedded paths For example, you can specify \file.lnk as the command-line argument When that’s à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à passed toPDF Merge and Split Unregistered the path intohttp://www.simpopdf.com Simpo ExpandFilePath(), the function splits Version - an array using the VBScript Split() function Next, each element of the array is checked to determine whether it is bracketed using < and > If it is, the SpecialFolders property of a WshShell object is used to resolve it to a true path Finally, the function reassembles the path using the Join() function.à à à à The rest of the script is basic A FileSystemObject is instantiated, and the à FileExists() method is called to check for the link file The output from the script is illustrated in Figure 11.11.à à à à à à à Figure 11.11: Result of running the chkscut.vbs script.à à à Ãà à à à Creating a New Shortcutà à The script example in Listing 11.11 shows how you can use the WSH objects to create new shortcuts The script creates two new shortcuts—one on the Windows desktop and one on the Windows Start menu.à à Listing 11.11 makescut.vbs—Code Sample to Create Shortcutsà à ’ FILE: makescut.vbsà ’ DESC: This script demonstrates how you can use VBScriptà ’ to create Windows shortcuts.à ’ AUTH: Thomas L Fredellà ’ DATE: 12/9/1998à ’à ’ Copyright 1998 Macmillan Publishingà à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à On Error Resume Nextà à ’à ’ Create shortcuts; we’ll use our own function to wrap shortcutà ’ creationà ’à Dim shortcutà à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Set shortcut = CreateShortcut("Desktop", _à "link to notepad.lnk", "notepad.exe")à If Not shortcut Is Nothing Thenà shortcut.Description = "Link to Windows notepad"à shortcut.Saveà Wscript.Echo "makescut.vbs: Created link to Windows notepad " & _à "on Desktop."à End Ifà à à à à à à à à à à If GetOS() = "WINDOWS_NT" Thenà Set shortcut = CreateShortcut("StartMenu", _à "Command Prompt.lnk", "cmd.exe")à If Not shortcut Is Nothing Thenà shortcut.Hotkey = "CTRL+SHIFT+0"à shortcut.Description = "Link to Command prompt"à shortcut.Saveà End Ifà Wscript.Echo "makescut.vbs: Created link to Windows NT " & _à "command prompt on Start Menu."à End Ifà à à à à à à à à à à à à à Wscript.Quit Err.Numberà à à à ’ -à ’ FUNC: CreateShortcut(sFolder, sFilename, sTarget)à ’ DESC: Creates a new shortcut object, saves it, thenà ’ returns it so additional attributes can be set.à ’ sFolder must be the name of a predefined Windowsà ’ folder, like "Desktop".à ’ -à Function CreateShortcut(sFolder, sFilename, sTarget)à Dim shell, sFolderPath, sFullPathà Dim sErrà On Error Resume Nextà Set shell = Wscript.CreateObject("WScript.Shell")à If Err.Number Thenà Wscript.Echo "Error: Unable to create shell object" & vbCrLf & _à " (" & Err.Number & ") " & Err.Descriptionà Exit Functionà End Ifà à à à à à à à à à à à à à à à à à à à ’à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à ’ Determine full Split Unregistered Version - http://www.simpopdf.com Simpo PDF Merge andpath to shortcut file using folder à settingsà ’ from shell objectà à ’à à sFolderPath = shell.SpecialFolders(sFolder)à à If Err.Number Thenà à sErr = "Error: Unable to retrieve path for à folder ’" & _à sFolder & "’." & vbCrLf & vbCrLf & _à à "Details - (" & Err.Number & ") " & à Err.Descriptionà shell.Popup sErr, 0, "CreateShortcut() Error", à 16à Exit Functionà à End Ifà à If Right(sFolderPath, 1) "\" Thenà à sFullPath = sFolderPath & "\" & sFilenameà à Elseà à sFullPath = sFolderPath & sFilenameà à End Ifà à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à ’à ’ Use shell object to create shortcut; check errors à à toà ’ ensure that it worksà ’à Set CreateShortcut = shell.CreateShortcut(sFullPath)à If Err.Number Thenà sErr = "Unable to create shortcut, path = ’" & _à sFullPath & "’." & vbCrLf & vbCrLf & _à "Details - (" & Err.Number & ") " & Err.Descriptionà shell.Popup sErr, 0, "CreateShortcut() Error", 16à Set CreateShortcut = Nothingà Exit Functionà End Ifà CreateShortcut.TargetPath = sTargetà CreateShortcut.Saveà End Functionà à ’ -à ’ FUNC: GetOS()à ’ DESC: Returns a string that represents the currentà ’ operating system.à ’ -à Function GetOS()à ’à ’ We’re going to get the OS using the currentà ’ environment, so we need a shell objectà à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à ’à à Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Dim shellà Set shell = Wscript.CreateObject("WScript.Shell")à If Err.Number Thenà Wscript.Echo "Error: Unable to create shell object" & vbCrLf & _à " (" & Err.Number & ") " & Err.Descriptionà Exit Functionà End Ifà GetOS = UCase(shell.Environment("OS"))à End Functionà à à à à à à à à à à à à Most of the logic in the previous script is embedded in two functions: CreateShortcut() and GetOS() The body of the script first calls CreateShortcut() to create a shortcut to the Windows Notepad on the desktop Next, it calls the GetOS() function to check whether the current operating system is Windows NT If it is Windows NT, the script creates a shortcut to the Windows NT command prompt on the Start menu.à à The CreateShortcut() function contains all the logic for creating a Windows shortcut It takes three arguments: the Windows folder in which the shortcut should be created, such as Desktop; the filename for the new shortcut file; and the target for the shortcut file Within the function, it instantiates a WshShell object The WshShell is used to find the absolute path to the Windows folder specified in the first argument and then it’s used to create a new shortcut object, which is saved and returned to the caller of CreateShortcut().à à The other primary function, GetOS(), returns a string that represents the current operating system The guts of it are simple; it creates a WshShell object, which contains an Environment property that we access to get the value of the "OS" environment variable.à à à à à à à à à Ãà à Noteà Creating new shortcuts using WSH is easy as you can tell from the preceding example Unfortunately, changing existing shortcuts isn’t à possible because the WshShell object doesn’t provide a capability to get an object for an existing shortcut.à à à à à Deleting a Shortcutà à The sample script in Listing 11.12 shows how you can delete a Windows shortcut The structure of the example is similar to the Check Shortcut example.à à Listing 11.12 delscut.vbs—Code Sample to Delete a Shortcutà à ’ FILE: delscut.vbsà ’ DESC: This script demonstrates how you can use VBScriptà ’ to delete Windows shortcuts.à ’ AUTH: Thomas L Fredellà ’ DATE: 12/9/1998à ’à ’ Copyright 1998 Macmillan Publishingà à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com On Error Resume Nextà à ’à ’ Check arguments & show usage if necessaryà ’à If Wscript.Arguments.Count Thenà Wscript.Echo "USAGE: delscut.vbs [shortcut file]"à Wscript.Echo ""à Wscript.Echo " This deletes the ’shortcut file’."à Wscript.Echo ""à Wscript.Quit 1à End Ifà à Dim sLinkFileà Dim filesysà à ’à ’ We’ll use routine from chkscut.vbs to expand pathà ’à sLinkFile = ExpandFilePath(Wscript.Arguments(0))à Wscript.Echo "delscut.vbs: Expanded path to link is ’" & _à sLinkFile & "’."à à ’à ’ Check to see if file exists using FileSystemObjectà ’à Set filesys = Wscript.CreateObject("Scripting.FileSystemObject")à If Not filesys.FileExists(sLinkFile) Thenà Wscript.Echo "delscut.vbs: The shortcut link file wasn’t found."à Elseà filesys.DeleteFile sLinkFile, Trueà If Err.Number = Thenà Wscript.Echo "delscut.vbs: The shortcut link file " & _à "was deleted successfully."à Elseà Wscript.Echo "delscut.vbs: Unable to delete shortcut " & _à "link file (" & Err.Number & ") " & Err.Descriptionà End Ifà End Ifà à ’ -à ’ FUNC: ExpandFilePath(sPath)à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à ’Simpo PDF Merge and Split Unregistered Versionexpandedà DESC: Returns a string that represents the - http://www.simpopdf.com à ’ file path.à à ’ à -à Function ExpandFilePath(sPath)à à On Error Resume Nextà à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à ’à ’ We need a shell object to expand special foldersà ’à Set shell = Wscript.CreateObject("WScript.Shell")à à à à à à Dim asPathSegments, iSeg, sSegà Dim sSpecialFolderà Dim shellà à à à ’à ’ First we’ll split the input path into an arrayà ’ of strings using ’\’ as a delimiter; this willà ’ make the search easy, because we’ll only have toà ’ iterate through an array, assuming the path isà ’ well-formedà ’à asPathSegments = Split(sPath, "\")à For iSeg = LBound(asPathSegments) To UBound(asPathSegments)à sSeg = asPathSegments(iSeg) à If Len(sSeg) > Thenà ’à ’ A special folder must be AT LEAST characters,à ’ but in reality will be more ala à ’à If (Left(sSeg, 1) = "") Thenà ’à ’ Attempt to expand this path segmentà ’à sSpecialFolder = Mid(sSeg, 2, Len(sSeg) - 2)à asPathSegments(iSeg) = shell.SpecialFolders (sSpecialFolder)à End Ifà End Ifà Nextà à ’à ’ Now we can re-assemble the path and return ità ’à ExpandFilePath = Join(asPathSegments, "\")à End Functionà à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com This delete shortcut script is almost identical to the check shortcut script The only differences are the messages and the use of the FileSystemObject.DeleteFile() method.à à Managing Foldersà à You’ve seen how easy it is to check, create, and delete Windows shortcuts Now you’ll take a look at how you can perform similar functions with folders When you understand how to manage shortcuts and folders with scripts, you will have the ability to write scripts that can reconfigure much of a user’s Windows experience from the desktop and Start menu perspective.à à Checking for a Folderà à To check for a folder, Listing 11.13 uses the FileSystemObject It provides a FolderExists() method that returns true if a folder exists, or false if it doesn’t.à à Listing 11.13 chkfldr.vbs—Code Sample to Check for a Folderà à ’ FILE: chkfldr.vbsà ’ DESC: This script demonstrates how you can use VBScriptà ’ to check for a folder.à ’ AUTH: Thomas L Fredellà ’ DATE: 12/9/1998à ’à ’ Copyright 1998 Macmillan Publishingà à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à On Error Resume Nextà à ’à ’ Check arguments & show usage if necessaryà ’à If Wscript.Arguments.Count Thenà Wscript.Echo "USAGE: chkfldr.vbs [folder path]"à Wscript.Echo ""à Wscript.Echo " This checks for the existence"à Wscript.Echo " of ’folder path’."à Wscript.Echo ""à Wscript.Quit 1à End Ifà à ’à ’ Check to see if folder exists using FileSystemObjectà ’à Dim sFolderPathà Dim filesysà Dim tExistsà à sFolderPath = Wscript.Arguments(0)à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à Set filesys Merge and Split Unregistered Version - http://www.simpopdf.com Simpo PDF = à Wscript.CreateObject("Scripting.FileSystemObject")à à If filesys.FolderExists(sFolderPath) Thenà Wscript.Echo "chkfldr.vbs: The folder ’" & _à sFolderPath & "’ was found."à Elseà Wscript.Echo "chkfldr.vbs: The folder ’" & _à sFolderPath & "’ doesn’t exist."à End Ifà à à à à à à à à à à à The chkfldr.vbs script is simple It begins with the standard argument check Next it instantiates a FileSystemObject, which is used for the FolderExists() method to check for a folder.à à Creating a New Folderà à Creating a folder is as easy as checking for a folder Examine the script in Listing 11.14, makfldr.vbs, and you’ll see the similarities.à à Listing 11.14 makfldr.vbs—Code Sample to Create a New Folderà à ’ FILE: makfldr.vbsà ’ DESC: This script demonstrates how you can use VBScriptà ’ to create a new folder.à ’ AUTH: Thomas L Fredellà ’ DATE: 12/9/1998à ’à ’ Copyright 1998 Macmillan Publishingà à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à à On Error Resume Nextà à ’à ’ Check arguments & show usage if necessaryà ’à If Wscript.Arguments.Count < Thenà Wscript.Echo "USAGE: makfldr.vbs [folder1] [folderN]"à Wscript.Echo ""à Wscript.Echo " This allows you to create one or more"à Wscript.Echo " folders."à Wscript.Echo ""à Wscript.Quit 1à End Ifà à ’à ’ Create a FileSystemObject; we’ll use it to create theà ’ new folder(s)à ’à Dim sFolderPathà à à à à à à à à à à à à à à à à à à à à à à à à à à ... User Login Scriptsà à Defining user login scripts is easy; they are simply standard WSH scripts Listing 11.1 provides a basic Hello World login script. à à Listing 11.1 Hello World Login Script? ?... you see how you can put this script into use as a login script. à à Setting Up Login Scriptsà à To set up login scripts, go into the Windows NT User Manager for domains Select a user, or multiple... Files setting for the Windows Explorer.à à à à Administering User Shortcuts and Foldersà à The Windows Scripting Host provides powerful capabilities to programmatically administer Windows shortcuts

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

Từ khóa liên quan

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

Tài liệu liên quan