27
January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355 Shell Scripting 101, Lesson 1 Windows shell scripting is a powerful language that can introduce you to the world of scripting. Even if you’ve never written code before, you can quickly perform tasks that would take much longer to perform in the GUI. In the next 10 lessons, I’ll cover the basics of shell scripting. In each lesson, I’ll give you practice exercises that can help you hone your new skills. The more you practice, the sharper your new skills will become. The shell scripting language that’s available in Windows 2000 and Windows NT is much more powerful than the shell scripting language that’s available in Windows 9x, MS-DOS, or OS/2. Some shell scripting commands in Win2K and NT don’t exist or have different or limited functionality in the other OSs. So, if you’re scripting in an environment that has Win9x, MS-DOS, or OS/2 machines, you’ll need to test your scripts carefully to make sure they function correctly. Setting Up Your Scripting Environment Before you start writing code, you need to set up your scripting environment. Open a command shell window, and right-click the title bar. Select Properties from the drop-down menu. On the Options tab, select the QuickEdit Mode check box. QuickEdit Mode lets you select text with your mouse and perform copy and paste operations. Next, select the Insert Mode check box. By selecting Insert Mode, you’ll insert rather than overwrite text as you type. Finally, click the Layout tab. Under Screen Buffer Size, adjust the Height to a value between 250 and 300. This height lets you scroll to see any command output that doesn’t fit in the normal window dimensions. After you make these adjustments, click OK. The Apply Properties dialog box that appears gives you two options. Select either Modify shortcut that started this window or Save properties for future windows with same title. (The option that the dialog box displays depends on how you launched the command shell window.) These modifications make the command shell window easier to work in. If you want to modify the appearance of the command shell window, you can use the options on the Font and Colors tabs in the Properties dialog box. To test the QuickEdit Mode you just enabled, copy the text Echo Hello World. Here is my first line of shell scripting code! then right-click anywhere in the command shell window. The text you copied will appear next to the command prompt. Press Enter to execute your first shell command. You’ve just run code from the command line. Now, let’s use a script (i.e., a .bat file) to run similar code. Open Notepad. Copy these four lines @Echo Off Echo Hello World. Here is my first line of shell scripting code! Echo Hello World. Here is my second line of shell scripting code! Echo Hello World. Here is my third line of shell scripting code! then paste them into the Notepad file. Select Save in the File menu. In the Save As dialog box that appears, type Hello.bat in the File name text box. Leave the default entry of Text Documents (*txt) in the Save as type text box. In the Save in drop-down menu, select Desktop and click Save. Close Notepad. The file Hello.bat now appears on your desktop. Position the file and your command shell window so that both are visible on your screen. Drag the file onto the command shell window. The path to the .bat file you just created appears at the command prompt ready to run. Dragging the file onto the command shell window is a shortcut for typing the path to the file. Click the command shell window so that you see the cursor, then press Enter to run the .bat file. o These two exercises demonstrate three important scripting concepts:

January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is

January 3, 2001   |   Dick Lewis   |   Feature   |   Instant Doc #16355

Shell Scripting 101, Lesson 1

Windows shell scripting is a powerful language that can introduce you to the world of scripting. Even if you’ve never written code before, you can quickly perform tasks that would take much longer to perform in the GUI. In the next 10 lessons, I’ll cover the basics of shell scripting. In each lesson, I’ll give you practice exercises that can help you hone your new skills. The more you practice, the sharper your new skills will become.

The shell scripting language that’s available in Windows 2000 and Windows NT is much more powerful than the shell scripting language that’s available in Windows 9x, MS-DOS, or OS/2. Some shell scripting commands in Win2K and NT don’t exist or have different or limited functionality in the other OSs. So, if you’re scripting in an environment that has Win9x, MS-DOS, or OS/2 machines, you’ll need to test your scripts carefully to make sure they function correctly.

Setting Up Your Scripting Environment Before you start writing code, you need to set up your scripting environment. Open a command shell window, and right-click the title bar. Select Properties from the drop-down menu. On the Options tab, select the QuickEdit Mode check box. QuickEdit Mode lets you select text with your mouse and perform copy and paste operations. Next, select the Insert Mode check box. By selecting Insert Mode, you’ll insert rather than overwrite text as you type. Finally, click the Layout tab. Under Screen Buffer Size, adjust the Height to a value between 250 and 300. This height lets you scroll to see any command output that doesn’t fit in the normal window dimensions.

After you make these adjustments, click OK. The Apply Properties dialog box that appears gives you two options. Select either Modify shortcut that started this window or Save properties for future windows with same title. (The option that the dialog box displays depends on how you launched the command shell window.)

These modifications make the command shell window easier to work in. If you want to modify the appearance of the command shell window, you can use the options on the Font and Colors tabs in the Properties dialog box.

To test the QuickEdit Mode you just enabled, copy the text

Echo Hello World. Here is my first line of shell scripting code!then right-click anywhere in the command shell window. The text you copied will appear next to the command prompt. Press Enter to execute your first shell command.

You’ve just run code from the command line. Now, let’s use a script (i.e., a .bat file) to run similar code. Open Notepad. Copy these four lines

@Echo Off Echo Hello World. Here is my first line of shell scripting code! Echo Hello World. Here is my second line of shell scripting code! Echo Hello World. Here is my third line of shell scripting code!

then paste them into the Notepad file. Select Save in the File menu. In the Save As dialog box that appears, type Hello.bat in the File name text box. Leave the default entry of Text Documents (*txt) in the Save as type text box. In the Save in drop-down menu, select Desktop and click Save. Close Notepad.

The file Hello.bat now appears on your desktop. Position the file and your command shell window so that both are visible on your screen. Drag the file onto the command shell window. The path to the .bat file you just created appears at the command prompt ready to run. Dragging the file onto the command shell window is a shortcut for typing the path to the file. Click the command shell window so that you see the cursor, then press Enter to run the .bat file.

o These two exercises demonstrate three important scripting concepts: o You can run only one line of code at a time from the command shell window. o You can use a .bat file to run one or more lines of code. o By default, lines of code in a .bat file execute sequentially from top to bottom. (You can use certain commands to

change this flow, but I’ll save that topic for another lesson.)

Learning the Echo and Rem Commands In the .bat file you executed, you might have noticed that the word Echo appears several times. Echo is a useful command that lets you display messages. As the codeEcho Hello World. Here is my first line of shell scripting code!shows, to display text, you specify the Echo command followed by the text you want to display. Any text between Echo and the line return will appear when you run the code.

Page 2: January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is

You can use the Echo command to turn the system’s command-echoing feature on and off. By default, the command-echoing feature is on. To turn the system’s command-echoing feature off, you use the Off parameter with the command name. To see the command-echoing feature and the Echo Off command in action, open Notepad. Copy the lines Echo Hello World. Here is my shell scripting code that demonstrates Echo On!Echo OffEcho Hello World. Here is my shell scriptingcode that demonstrates Echo Off!and paste them into the Notepad file. Save the file as HelloAgain.bat. Drag the file onto the command shell window, click the window, then press Enter to run HelloAgain.bat. In the results, note that the third line of code is visible in the command shell window but not the command that launched it. As this example shows, you can strategically use the Echo Off command to send only a command’s output to the screen. Like a light switch, after you turn the command-echoing feature off, it stays off until you turn it back on. To turn the command-echoing feature back on, you use the Echo command with the On parameter: Echo On You can turn the command-echoing feature off for just one line by preceding the Echo Off command with the at (@) sign: @Echo OffIn this case, you don’t have to use Echo On to turn the command-echoing feature back on. It goes back on automatically. Another useful command to learn is Rem. This command lets you insert remarks (i.e., comments) in a .bat file. A comment is text that’s not meant to be executed but rather to help explain something in the .bat file. Systems administrators often use comments to explain how a .bat file works or how to configure the .bat file for a particular system. Using the Rem command is simple. At the beginning of the line, you specify the command followed by the comment Rem The comment goes here.Any text between Rem and the line return will not be executed. Another way to comment out a line is to use a double colon (::):: The comment goes here.Practice Exercises

1. From Notepad, open Hello.bat. Remove the @Echo Off command or precede this command with the Rem command. Run Hello.bat to see the results.

2. Remove @ from the @Echo Off line. Run Hello.bat to see the results. 3. Comment out the @Echo Off line, and place @ in front of each Echo command. Run Hello.bat to see the results. 4. Drag HelloAgain.bat onto the command prompt window, then press the Escape key and observe the result. (Escape clears

the entry.)

February 2, 2001   |   Dick Lewis   |   Feature   |   Instant Doc #19840

Shell Scripting 101, Lesson 2

In Lesson 1, I introduced you to the Windows shell scripting language. You can use this scripting language to write scripts (i.e., .bat or .cmd files), such as those you wrote in Lesson 1. You can trace the .bat extension back to the batch commands in MS-DOS. Batch files for earlier OSs such as MS-DOS and Windows 95 had limited functionality. Starting with Windows NT, however, the shell scripting language became much more powerful. With this new functionality came the new .cmd extension.

In Windows 2000 and NT, you can save and run code with a .bat or .cmd extension. Whether a .bat or .cmd file, the code runs the same. However, if you create a .cmd file in a Win2K or NT system, it won’t work on an earlier OS. In addition, if you write and save code as a .bat file on Win2K or NT but run it on an earlier OS, some commands might have limited functionality or might not work. So, if you’re writing scripts for a mixed environment, you need to test those scripts carefully to make sure they function correctly. Scripts obtain information from four basic sources:

Information you write, or hard-code, into the script Information from environment variables Information from arguments Information from executed commands (i.e., command output)

Page 3: January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is

In this lesson, I discuss how you can hard-code information into your scripts and how you can use environment variables. I’ll discuss how to use arguments in Lesson 3 and how to use command output in Lesson 4.Hard-Coding Information In a script, you often have to specify computer or user information (e.g., drive, filename, username). When you code this information directly into your script, you’re hard-coding the information. Take, for example, the codeEcho My NT installation is in the C:\winnt directory.In this code, the pathname C:\winnt is hard-coded.Using Environment Variables NT’s online Help file defines an environment variable as, "A string consisting of environment information, such as a drive, path, or filename, associated with a symbolic name that can be used by Windows NT." Environment variables let you easily access environment information that the registry stores. The registry stores system-related environment information in the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment subkey and user-related environment information in the HKEY_CURRENT_USER\Environment subkey.You can use the Set command to see the environment variables defined on your computer. Open the command shell window, typeSetat the command prompt, then press Enter. A list of the environment variables appears.You can use the Control Panel System applet to add more environment variables. Open the applet, and select the Environment tab. Type the environment variable’s symbolic name in the Variable field and its environment information in the Value field. Click Set.In a script, you can use an environment variable’s symbolic name to access that variable’s value. For example, if you run the codeEcho My NT installation is in the C:\winnt directory.in the command shell window, you receive the message My NT installation is in the C:\winnt directory. Instead of hard-coding the installation pathname, you can use the environment variable that contains this information: SYSTEMROOT. To retrieve and use an environment variable's value in code, you need to enclose the environment variable's symbolic name in percent (%) signs. So, to retrieve the NT installation pathname, you can run the codeEcho My NT installation is in the %SYSTEMROOT% directory.If you installed NT in the default location, you receive the message My NT installation is in the C:\winnt directory. If you’ve changed the location, the message will display that pathname instead of C:\winnt.Let’s look at another example. Suppose you want to create a text file, test.txt, in the Temp directory on your computer. If you run the codeEcho Here is the test file you created. > C:\temp\test.txtthe system creates test.txt in the C:\temp folder; this file has one line that reads Here is the test file you created. However, if your Temp folder isn’t in the specified location (i.e., C:\temp), this code will fail. To avoid possible failure, you can use the TEMP environment variable instead of hard-coding the Temp folder’s location. If you run the codeEcho Here is the test file you created. > %TEMP%\test.txtthe system creates test.txt in the Temp folder, no matter the location of that folder.In the last two code examples, note the use of the greater than (>) sign. The > sign is a redirection symbol that tells the system to redirect the output of the preceding command (in this case, the Echo command) to the specified file.Another useful environment variable is USERPROFILE, which contains profile information about the currently logged-on user. For example, you can use this variable with the Dir command. The Dir command lists all the subdirectories and files in the directory you specify. If you specify USERPROFILE as the directory with the codeDir %USERPROFILE%you receive the contents of the Profiles directory for the currently logged-on user. If you want the username of the currently logged-on user and the name of the computer the user is logged on to, you can run the codeEcho A user called %USERNAME% is logged into %COMPUTERNAME% now.As these examples show, environment variables are handy for retrieving information about currently logged-on users and their computers. Environment variables are also handy for temporarily holding a value so that you can pass information to script as an argument. I cover how to use environment variables for this purpose in Lesson 3.Practice Exercises

1. Run the Set command from the command prompt to view the environment variables on your computer. 2. Run the Set command and output the results to a text file. (Here’s a hint: Use the > redirection symbol.)

March 1, 2001   |   Dick Lewis   |   Feature   |   Instant Doc #20142

Shell Scripting 101, Lesson 3

 

Page 4: January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is

In Lesson 2, I showed you how to use system-provided environment variables such as USERNAME and COMPUTERNAME to retrieve information about currently logged-on users and their computers. You can also use environment variables for two additional purposes:

You can create an environment variable to represent a specified value. You can use an environment variable to temporarily hold a value so that you can pass information to a script as an

argument.

Creating Environment Variables to Represent a Specified Value To create environment variables to represent a specified value, you need to use the Set command. Using the Set command with environment variables is a great way to make your lines of code shorter, easier to read, and simpler to change.For example, suppose you’ve updated a file called listofstuff.txt on your server (\\H10server\stuff\listofstuff.txt) and now you must update a copy of that file on the D drive (D:\stuff\morestuff\mystuff\yourstuff\lotsofstuff\listofstuff.txt). The script must delete the old file if it exists, then copy the updated file. Listing 1 shows how this script looks if you hard-code the file’s pathname each time. As Listing 1 illustrates, this code is long and difficult to read. In addition, this code is difficult to edit if you need to change the D drive’s pathname because you must change each occurrence.A better approach is to create an environment variable for the commonly occurring pathname. As the script in Listing 2 shows, you can use the Set command to create the StuffFile environment variable, which contains the pathname "D:\stuff\morestuff\mystuff\yourstuff\lotsofstuff\listofstuff.txt". Enclosing the pathname in quotation marks handles any spaces in the path. Without quotation marks, a pathname with a space will cause the script to fail.After you create the environment variable, you simply specify that variable’s name enclosed in percent (%) signs each time you want to include the pathname. The percent signs let you retrieve and use the environment variable’s value.Creating an environment variable instead of hard-coding the pathname can save a lot of space, especially in scripts that use long pathnames often. Even better, if the pathname changes, you need to change only one occurrence: the pathname in the Set command.Limiting the Environment Variable’s Scope By default, an environment variable you create with the Set command affects your entire system—that is, the environment variable has a global scope. You can use the Setlocal and Endlocal commands to make an environment variable affect only that script or a portion of it. In other words, you make the environment variable have a local scope. I highly recommend that you use the Setlocal and Endlocal commands to keep your Set commands from accidentally affecting System variables or causing a script that’s run in the same command shell window from inheriting values from an earlier run of a similar script.To make an environment variable apply to an entire script, you place the Setlocal command before the Set command and the Endlocal command at the end of your script, as Listing 3 shows. To make the environment variable apply to a certain portion of the script, you place the Setlocal command before the Set command and the Endlocal command at the point at which you want the environment variable’s scope to end. Take, for example, the code in Listing 4. The Echo %TestVariable% command is no longer under the environment variable’s scope. As a result, if you run the code in Listing 4, the %TestVariable% won’t have a value. As this example illustrates, if you’re limiting the environment variable’s scope to only a portion of a script, you need to make sure that the code you exclude doesn’t need that variable’s value. For this reason, I recommend that you use the Setlocal command before any Set commands and the Endlocal command at the end of your script.Using an Environment Variable to Temporarily Hold a Value A special group of environment variables are the argument-holding variables %0 through %9. You can use these variables to bring input into your script at runtime. For example, suppose you want to run the script in Listing 2, but you want to change the pathname each time the script runs. Instead of opening the file and editing the Set command each time, you can use an argument-holding variable. As the script Test.bat in Listing 5 shows, you don’t include the Set command and you use %1 instead of %StuffFile%. Then, when you run Test.bat, you type the launch commandTest.bat "D:\stuff\morestuff\mystuff\yourstuff\lotsofstuff\listofstuff.txt"in the command-shell window. When the script runs, the %1 variable brings your external input (i.e., "D:\stuff\morestuff\mystuff\yourstuff\lotsofstuff\listofstuff.txt") into the script.If you want to use additional arguments, you add the next consecutive argument-holding variable to the code and that variable’s value to the launch command. You’re limited to 10 arguments (i.e., %0 through %9). You might be wondering, "What is the value of %0?" To learn the answer and to see how to use two arguments, create the script Test2.bat that Listing 6 shows. Then use the launch commandTest2.bat "The First Argument" "Another Argument"to run Test2.bat. As Figure 1 shows, if you launch the script from the directory in which you placed the script, the value of %0 is the script’s filename. If you launch the script from a different directory, the value of %0 is the script’s pathname.Practice Exercises

Page 5: January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is

1. Write code that combines a system-provided environment variable with a user-created environment variable. For example, write code that first uses the TEMP environment variable to run the Dir command against your Temp folder, then uses the Set command to create an environment variable that points to the folder in which you want to copy all the .tmp files.

2. In the pathname "D:\stuff\morestuff\mystuff\yourstuff\lotsofstuff\listofstuff.txt" in Listing 2, remove the quotation marks and intentionally insert a space. Run the code, and observe the results.

Figure 1

Listing 1:: Listing 1. Hard-Coding the Pathname on Each Occurrence

If Exist D:\stuff\morestuff\mystuff\yourstuff\lotsofstuff\listofstuff.txtDel D:\stuff\morestuff\mystuff\yourstuff\lotsofstuff\listofstuff.txt

Copy \\H10server\stuff\listofstuff.txt D:\stuff\morestuff\mystuff\yourstuff\lotsofstuff\listofstuff.txt

Listing 2:: Listing 2. Creating the StuffFile Environment Variable to Represent the Pathname

Set StuffFile="D:\stuff\morestuff\mystuff\yourstuff\lotsofstuff\listofstuff.txt"If Exist %StuffFile%

Del %StuffFile%Copy \\H10server\stuff\listofstuff.txt %StuffFile%

Page 6: January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is

Listing 3:: Listing 3. Making the Environment Variable Affect the Entire Script

SetlocalSet TestVariable=10Echo %TestVariable%Endlocal

Listing 4:: Listing 4. Making the Environment Variable Affect Only a Portion of the Script

SetlocalSet TestVariable=10EndlocalEcho %TestVariable%

Listing 5:: Listing 5. Test.bat

If Exist %1Del %1

Copy \\H10server\stuff\listofstuff.txt %1

Listing 6:: Listing 6. Test2.bat

Echo The first argument is: %1Echo The second argument is: %2Echo The zero argument is: %0

Page 7: January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is

April 2, 2001   |   Dick Lewis   |   Feature   |   Instant Doc #20530

Shell Scripting 101, Lesson 4

Shell scripting commands often produce output. By default, the system directs a command's output to the console screen. For example, if you run the command

Echo Fred was herethe screen displays the text Fred was here. However, you can easily redirect a command's output to a file with redirection symbols. Two commonly used redirection symbols are the greater than (>) sign and the double greater than (>>) sign.The > and >> Redirection Symbols To redirect a command's output to a file, you place the > redirection symbol after the command, then specify the file after the symbol. For example, the commandEcho Fred was here > C:\fredreport.txtsends the Echo command's output (i.e., the text Fred was here) to the fredreport.txt file on the C drive rather than displaying the output on screen. If this text file doesn't exist, the system automatically creates it. If this text file already exists, the system overwrites the file's existing content with the command's output. Thus, if you run the Echo Fred command three times, then examine the content of C:\fredreport.txt, you'll find only one line of text. Because the system overwrites existing content, the > redirection symbol is useful when you want to create a report and delete any old version that might exist.If you want to append a command's output to a file's existing content, you can use the >> redirection symbol. For example, the commandEcho Barney was here >> C:\barneyreport.txtappends the text Barney was here to the existing content of C:\barneyreport.txt if that text file already exists. If that text file doesn't exist, the system automatically creates it and adds the command's output. If you run the Echo Barney command three times, then examine the content of C:\barneyreport.txt, you'll find three lines of text. Because the system appends rather than overwrites content, the >> redirection symbol is useful when you want to create a report in which you plan to add text, either during the current script run or in a future script run.Let's experiment with adding text to an existing report during a script run. Open Notepad. Type these three linesEcho Pebbles was here > C:\pebblesreport.txtEcho. >> C:\pebblesreport.txtEcho Pebbles was here again>> C:\pebblesreport.txtinto the Notepad file. Select Save in the File menu. In the Save As dialog box that appears, type Pebbles.bat in the File name text box. Leave the default entry, Text Documents (*txt), in the Save as type text box. From the Save in drop-down menu, select Desktop. Click Save, then close Notepad.You've now created the script Pebbles.bat. Here's how the script works. The first line of code uses the > redirection symbol to create the file C:\pebblesreport.txt, then adds the text Pebbles was here to that file. The next line inserts a blank line into the file. By placing a period directly after the Echo command, you're telling the system to output a blank line, which the >>redirection symbol appends to the file. The last line appends the text Pebbles was here again to the file.Let's run Pebbles.bat. On your desktop, position the file and your command shell window so that both are visible in the screen. Drag the file onto the command shell window. Click the command shell window so that you see the cursor, then press Enter to run Pebbles.bat. Figure 1 shows the content you'll see if you open pebblesreport.txt.Redirection Options Up to this point, you've redirected the various commands' output to a text file. You're not limited to text files, though; you can redirect a command's output to many types of files. You can even redirect command output to NUL.Redirecting output to different file types. You can redirect a command's output to many different file types. However, you might need to provide special formatting instructions. For example, Listing 1 contains a script, HelloWorld.bat, that redirects the Echo commands' output to an .html file. Note that, in addition to using the Echo command with text, the script uses the Echo command with the USERNAME and COMPUTERNAME environment variables that I discussed in "Shell Scripting 101, Lesson 2," Instant Doc ID 19840.To format the .html file, the script uses HTML code to specify the headers and body text. Because HTML code uses several symbols (e.g., <, >, /) that the shell scripting language reserves as special shell characters (i.e., characters that have special meaning in the Windows system), the script uses a caret (^) to flag, or escape out, those HTML symbols. The caret tells the system to treat the item that follows as an HTML symbol and not a reserved shell character.To see a sample .html file that HelloWorld.bat produces, you can download and run this script on your machine. To download the script, click the Download the code link in the Article Information box. After you copy HelloWorld.bat from the 20530.zip file to your desktop, execute the script following the instructions I gave you for running Pebbles.bat.

Page 8: January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is

Redirecting output to NUL. In the sample code thus far, you've redirected output that you need to complete a task, such as creating a report. However, commands can produce output that you might not need. For example, a command can produce output that simply notes its successful execution (i.e., standard output) or any problems encountered (i.e., error output). Such output can produce clutter and even be confusing when it appears onscreen, so suppressing that output might be desirable. You can suppress output by redirecting it to a device named NUL. You can think of NUL as the command-shell trash can. When you redirect output to NUL, the output isn't visible onscreen.Let's first look at how to suppress a command's standard output. Suppose you want to map a drive to a share, so you type the commandNet Use * \\servername\sharenameat the command prompt, where servername is the name of the target server and sharename is the name of the target share. When you run this command, the system maps the specified drive to the specified share, then sends the standard output The command completed successfully to your screen. If you don't want to clutter your screen with that output, you can suppress it by appending > NUL to the Net Use command:Net Use * \\servername\sharename > NULWhen you run this command, the system sends the standard output to the command-shell trash can instead of your screen. Now let's look at how to suppress a command's error output. Let’s intentionally force an error by trying to map a drive to a share that doesn't exist. At the command prompt, typeNet Use R: \\servername\nosharewhere servername is the name of your server and noshare is a fictitious share. When you run this command, your screen will display error output that reads something like System error 67 has occurred. The network name cannot be found. To suppress that error output, you can append 2> NUL to the command:Net Use R: \\servername\noshare 2> NULWhen you run this command, the system redirects the error output to the command-shell trash can.For More Examples of Redirection in Action The 20530.zip file contains another script, BootIniTester.bat, that provides more examples of how redirection symbols work. This script tests the C and D drives on your machine to see whether the boot.ini file is present, then creates a report detailing the results.Homework Assignments

1. Use HelloWorld.bat as a template to create a script that displays the values of several more environment variables. 2. Run a command that you know will fail, such as

Copy C:\fred47.txt D:\fred.txt >NULRemove >NUL, and run the command again. Compare the output of the two commands to see the difference.

Figure 1

Listing 1# Listing 1. HelloWorld.bat

Echo ^<body^> >C:\HelloWorld.htmlEcho ^<h1^> >>C:\HelloWorld.htmlEcho Hello World! ^<BR^> >>C:\HelloWorld.html

Page 9: January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is

Echo My name is %USERNAME%. >>C:\HelloWorld.htmlEcho I'm sending you this message from %COMPUTERNAME%. >>C:\HelloWorld.htmlEcho ^<^/h1^> >>C:\HelloWorld.htmlEcho ^<^/body^> >>C:\HelloWorld.html

April 24, 2001   |   Dick Lewis   |   Feature   |   Instant Doc #20781

Shell Scripting 101, Lesson 5

Occasionally, you might need to perform math in a shell script. In Lesson 3, I showed you how to use the Set command to create custom environment variables. You can also use the Set command to perform simple math calculations, such as addition, by including the /a switch. This switch tells the scripting engine to evaluate the integers that follow as numerical expressions.

For example, if you run the code

Set /a Fred=2+3Echo %Fred%you receive the sum of these two numbers (i.e., 5). If you run the code without the /a switchSet Fred=2+3Echo %Fred%you won't receive a result of 5 but rather the string 2+3. Without the /a switch, you're merely making the Fred environment variable contain the string 2+3.The Set /a command performs math calculations with integers only. The calculations you can perform with this command are

addition (use the + operator) subtraction (use the - operator) multiplication (use the * operator) division (use the / operator) modulus (i.e., the process of dividing two numbers and returning only the remainder—use the % operator)

The Set /a calculations are precise as long as the integers you’re calculating are 10 or fewer digits.Combining the Set and If Commands Systems administrators often use the Set /a command in conjunction with the If command when they perform math calculations. The If command executes specific code if a certain condition exists (i.e., the conditional code evaluates to a true statement). The If command has many syntax versions, but the basic syntax isIf Condition CodeToExecutewhere Condition is the conditional code to evaluate and CodeToExecute is the code you want to run if the conditional code evaluates to a true statement. When you combine a Set /a command with an If command, you can use these abbreviations:

EQU (equal to) NEQ (not equal to) LSS (less than) LEQ (less than or equal to) GTR (greater than) GEQ (greater than or equal to)

For example, if you run the codeSet /a Fred=2+3Set /a Wilma=2*3If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilmayou receive the result Fred is less than Wilma. However, if you run the codeSet /a Fred=2+3Set /a Wilma=2*3If %Fred% GTR %Wilma% Echo Yes, Fred is less than Wilmayou don't receive any result because the conditional code evaluates to a false statement.In Lesson 6, I’ll cover the If statement in greater detail. For now, let's look at a more practical example of how you can use the Set /a and If commands together.

Page 10: January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is

A Practical Example Suppose you want a script to loop a certain number of times. CountLoops.bat in Listing 1 illustrates how you can use the Set /a and If commands to prompt that script to run a certain number of times.CountLoops.bat uses several new concepts: counters, the GoTo command, and labels. You can use counters to track the number of times a script completes an operation. For example, you can use counters to capture how many user accounts a script adds or how many files are in a folder. An important point to remember when you use counters is that you need to initialize the counter before you use it by including the commandSet /a counter=0at the beginning of the script. This command sets an initial value (in this case, 0). If you use the counter without setting an initial value, you can receive some unusual errors.By default, the scripting engine reads code from top to bottom. However, you can use the GoTo command and labels to change a script’s flow of execution—you can jump to any location in the script. You place the GoTo command at the point at which you want to jump to a different part of the script. The label marks the spot to which you want to jump. The GoTo command’s syntax is simplyGoTo :LabelYou can use any term for the label as long as you preface it with a colon (:). Although you can use spaces in the label, you can’t use commas, semicolons, or other separators. The label can be any length. However, the scripting engine reads only the first eight characters, so it reads the labels :MyLabel01 and :MyLabel02 both as :MyLabel0, which can cause errors in a script.In Listing 1, the code’s flow needs to return to the top of the script whenever the value of the counter variable is less than 10. So, I used the GoTo command with the label :Top to move the flow to that point, where the execution again proceeds downward.Homework Assignments1. Run the commandsSet /?|MoreandIf /?|Moreto see all the options that the Set and If commands provide.2. Download CountLoops.bat by clicking the Download the code link in the Article Information box. Comment out the counter initialization lineSet /a counter=0by prefacing it with a double colon (::) or the word Rem. Run the script several times in the same command-shell window to see the errors that result.

Listing 1:: Listing 1. CountLoops.bat

@Echo OffSet /a counter=0:TopSet /a counter=%counter%+1Echo Running the routine for pass number %counter%If %counter% LSS 10 GoTo :TopEcho Run completePause

June 4, 2001   |   Dick Lewis   |   Feature   |   Instant Doc #21310

Shell Scripting 101, Lesson 6

In "Shell Scripting 101, Lesson 5" (http://www.winscriptingsolutions.com, InstantDoc ID 20781), I introduced you to the If command. You‘ll probably use this command frequently in your scripts because its many clauses and switches make it a powerful tool. Here are some examples of how you can use this key command.

Page 11: January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is

Testing for a False Statement As I discussed in Lesson 5, the If command executes the specified code if the specified condition exists. If you’d rather execute code if a condition doesn’t exist, you can use the If command with the Not clause. The syntax is

If Not Condition CodeToExecutewhere Condition is the conditional code and CodeToExecute is the code you want to run if the conditional code evaluates to a false statement.For example, the following code sample tests whether you’ve installed Windows 2000 or Windows NT into a different directory location:If Not Exist C:\winnt Echo You’ve installed Windows todifferent directory location than the default.This code sample not only demonstrates the use of If Not but also introduces how to test for the existence of folders and files.Testing for the Existence of Folders and Files You can use the If command with the Exist clause to test whether certain folders or files exist. The syntax isIf Exist Condition CodeToExecuteFor example, suppose you want to test whether the Winnt folder is on the C drive. You can use the codeIf Exist C:\winnt Echo The Winnt folderis on the C drive.If that folder exists, the Echo command displays the message The Winnt folder is on the C drive.To broaden the scope of an existence test, you can use wildcards, such as the asterisk (*), in the folder name or filename. For example, if you can remember the name but not the extension of a file, you can still test for that file’s existence. The codeIf Exist C:\boot.* Echo The boot.* file is onthe C drive.tests whether any file on the C drive has the filename boot.Testing Whether the Last Command Completed Successfully You can use the If command with the Errorlevel clause to determine whether the preceding command executed successfully. Most shell-scripting commands return a number, or error-level value, when they execute. The error-level value of 0 indicates success; the error-level value of 1 or higher indicates failure. With the Errorlevel clause, the If command tests whether the preceding command’s error-level value is equal to or greater than the number you specify. You use the syntaxIf Errorlevel number CodeToExecutewhere number is the number you want the last command’s error-level value to be equal to or greater than. Take, for example, the codeCopy C:\fred.txt C:\temp\fred.txtIf Errorlevel 1 Echo Last command didn’t complete successfully.If the Copy command returns an error-level value of 1 or higher (i.e., the command failed to copy the C:\fred.txt file to the C:\temp folder), the Echo command displays the message Last command didn’t complete successfully. Because a few shell-scripting commands don’t return error-level values, you need to test your code carefully to ensure the Errorlevel clause is working correctly.Testing Whether Two Strings Are the Same You can use the If command to test whether two strings are the same, and if they are, execute the specified code. The syntax for this usage isIf "string1" == "string2" CodeToExecutewhere "string1" and "string2" are the strings or environment variables to compare. Note the use of the quotes. When you use the If command to test strings, a good practice to follow is to enclose the strings and environment variables in quotes. The If command will fail if a string contains spaces and you don’t enclose that string in quotes. Similarly, the If command will fail if a variable contains spaces or is empty and you don’t enclose that variable in quotes.Here’s an example of how to use the If command for string comparisons:Set EV1=Fred SmithIf "%EV1%" == "Fred Smith" Echo These two strings are the same.The string comparison is case sensitive. If you run the codeSet EV1=Fred SmithIf "%EV1%" == "Fred smith" Echo These two strings are the same.the Echo command won’t execute because the string comparison is a false statement. You can use the /i switch to disable the case sensitivity with code such asSet EV1=Fred SmithIf /i "%EV1%" == "fred smith" Echo These two strings are the same.

Page 12: January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is

If you want to use the If statement to detect a negative condition, you can add the Not clause. For example, the codeSet EV1=Fred SmithIf Not "%EV1%" == "fred smith" Echo These two strings are different.tests whether the two strings are the same. If they aren’t the same, the If command executes the Echo command.Homework Assignments

1. Type or copy the lines 2. Copy C:\fred.txt C:\temp\fred.txt

If Errorlevel 1 Echo Last command didn’t complete successfully.Copy C:\fred.txt C:\temp\fred.txtIf Not Errorlevel 1 Echo Last command completed successfully.into a Notepad file, and save it as ErrorlevelTest.bat. (For step-by-step instructions on how to create and run a .bat file, see "Shell Scripting 101, Lesson 1," http://www.winscriptingsolutions.com, InstantDoc ID 16355.) Run ErrorlevelTest.bat without creating a fred.txt file for the Copy command to copy. Next, create a fred.txt file, place it on the C drive, and run ErrorlevelTest.bat again. Compare the results of the two runs.

3. Explore what happens when you don’t include quotes around the strings or variables in a string comparison. For example, try running the code

4. Set EV1=Fred SmithIf %EV1% == Fred Smith Echo These two strings are the same.and see what happens.

5. Explore what happens when you have an empty string in a string comparison. Try running the code 6. Set EV1=IF "%EV1%" == "Fred Smith" Echo

These two strings are the same.and see what happens.

7. Try to write code that detects whether your OS is NT. Here’s a hint: Use the Set command to locate an environment variable that gives you the OS, and use that variable in an If statement.

June 28, 2001   |   Dick Lewis   |   Feature   |   Instant Doc #21630

Shell Scripting 101, Lesson 7

You can easily join commands with command symbols. You can use four symbols: pipe (|), ampersand (&), double ampersand (&&), and double pipe (||).

The | Symbol The | symbol pipes the output from one command (Command A) to another command (Command B). You place the | symbol between the commands:

Command A | Command BYou often have to filter a command’s output before using it. Thus, you’ll probably use the | symbol often to pipe output to the Find command. The Find command searches a command’s output (or text from an input file) for the string you specify. The Find command displays any line that contains the string and discards all the other lines.For example, suppose you want to know when the C:\winnt directory was created. As I discussed in "Shell Scripting 101, Lesson 2," the Dir command lists information, including creation date and time, about the subdirectories and files in the specified drive or directory. In this case, you use the commandDir /ad C:\The /a switch followed by the letter d specifies that you want to list only directories on the C drive.You now have the information you want, so you just need to pipe it to the Find command to filter out the information you don’t want. As the commandDir /ad C:\ | Find /i "winnt"shows, you use the | symbol to pipe the Dir command’s output to the Find command and specify "winnt" as the string for which to search. You need to enclose the string in quotes. The /i switch after Find makes the search case insensitive. As Figure 1 shows, when you run this command, you receive just the line that contains information about the \winnt directory.

Page 13: January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is

The & Symbol If you want to execute commands consecutively (e.g., Command A, then Command B), you place the & symbol between the commands:Command A & Command BYou’re not limited to joining only two commands. You can join any number of commands. For example, you can use the & symbol to place the three commandsEcho FredEcho WilmaEcho Barneyon one lineEcho Fred & Echo Wilma & Echo BarneyWhat are the benefits of putting commands together on the same line? Joining commands saves space in scripts. For example, suppose you want to test to see whether the C:\boot.ini file exists. If the file exists, you want to display the names Fred, Wilma, and Barney onscreen. If the file doesn't exist, you want to display the name Dino onscreen. As Listing 1 shows, if you don’t use the & symbol to join the commands, you need eight lines of code to accomplish this task. If you use the & symbol, you accomplish the same task with only three lines of code, as Listing 2 shows. In addition to the space advantage, the code in Listing 2 is much easier to read. You can mentally picture that the three Echo commands will execute if C:\boot.ini exists. (If you’re unfamiliar with the GoTo and If Exist commands in Listing 1 and Listing 2, see "Shell Scripting 101, Lesson 5" and "Shell Scripting 101, Lesson 6," respectively.)The && Symbol You use the && symbol to specify that you want to run Command A, and if Command A is successful, you want run Command B. In other words, Command B runs only if Command A succeeds. Although the && symbol’s syntaxCommand A && Command Blooks similar to the & symbol’s syntax, the two symbols are quite different. The best way to see the difference is to use the & and && symbols in the same code. If you run the codeDir /ad M:\ & Echo An M drive exists the Echo command displays the message An M drive exists (i.e., Command B) whether or not the Dir command (i.e., Command A) executes successfully. If you run the same code but this time with the && symbolDir /ad M:\ && Echo An M drive existsthe Echo command displays the message An M drive exists only if the Dir command executes successfully (i.e., you have an M drive). If you don't have an M drive, the Echo command doesn’t execute and you don’t receive the message.The || Symbol The syntax for the || symbol isCommand A || Command BThe || symbol is similar to the && symbol in that Command B’s execution hinges on Command A’s results. However, with the || symbol, Command B’s execution hinges on Command A’s failure rather than its success. In other words, Command B runs only if Command A fails. For example, if you run the codeDir /ad M:\ || Echo An M drive doesn’t exist.the command processor displays the message An M drive doesn’t exist only if the Dir command fails.Homework Assignments

1. Explore what happens when you add the /v switch to the Find command. Try running the command

Dir /ad C:\ | Find /i /v "winnt"and compare the results with those of the Find command you ran previously.

2. Find all the folders in the \winnt directory that don’t contain the string "drivers" in the folder name. Here’s a hint: Use the | symbol to chain together several Find commands.

Figure 1

Page 14: January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is

Listing 1:: Listing 1: Code without the & Character

If Exist C:\boot.ini GoTo :SendmessageEcho DinoGoTo :Last:SendmessageEcho FredEcho WilmaEcho Barney:Last

Listing 2:: Listing 2: Code with the & Character

If Exist C:\boot.ini Echo Fred & Echo Wilma & Echo Barney & GoTo :LastEcho Dino:Last

August 1, 2001   |   Dick Lewis   |   Feature   |   Instant Doc #21984

Shell Scripting 101, Lesson 8

The For command is a powerful shell scripting command because it’s versatile. Let’s look at some common uses of the For command. Specifically, let’s look at how to use the For command with the /d switch and with the /f switch. Along the way, you’ll learn about the Ping command.

Using the For /d Command Suppose you want to test the connections to five file servers (i.e., fileserv1, fileserv2, fileserv3, fileserv4, and fileserv5). If you’ve installed the TCP/IP protocol in your network, you can use the Ping command to verify the connections. The Ping command’s

 

Page 15: January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is

syntax is

Ping computernamewhere computername is the name of the server you want to ping. By default, the Ping command sends up to four ping packets to the computer. Pinging five file servers up to four times can waste time and bandwidth, so let’s ping each server only once. To change the default number of ping packets, you use the –n parameter, which lets you specify the number of ping packets to send. To ping each server once, you can use the codePing -n 1 fileserv1Ping -n 1 fileserv2Ping -n 1 fileserv3Ping -n 1 fileserv4Ping -n 1 fileserv5To shorten this code from five lines to one line, you can use the For command. The For command has different syntaxes for different purposes. In this case, the syntax to use isFor [/d] %variable in (set) Do commandYou use this particular syntax to iterate through a set of files or directories and perform a command for each file or directory in that set. Let’s look at the individual segments in this syntax.For [/d]. When you use the For command, the command processor assumes you want to iterate through files by default. To tell the command processor you want to iterate through directories, you include the optional /d switch. (In syntax, placing a switch or parameter in square brackets means it’s optional.) In the For command for the ping test, you need to include the /d switch.%variable. The %variable parameter represents an iterator variable. An iterator variable serves as a temporary container for data that you've captured in a For command. In other words, an iterator variable exists only within that particular For command. Typically, the first iterator variable is named %i; subsequent iterator variables proceed through the alphabet from that point (e.g., %j, %k). When you use iterator variables, you need to remember two conventions. First, the letter must be lowercase. Second, if you’re running the For command from the command-shell window, you use only one percent sign (e.g., %i). In a script, you must use two percent signs (%%i); otherwise, the script will fail.in (set). In this segment, the (set) parameter represents the files or directories through which you want the For command to iterate. In the For command for the ping test, the set is (fileserv1 fileserv2 fileserv3 fileserv4 fileserv5). The For command will iterate through this set, temporarily assigning each server name to the %i variable.Do command. In this segment, the command parameter represents the command sequence that you want to execute for each file or directory in the set. In the For command for the ping test, the command sequence isDo @Ping -n 1 %i Instead of specifying a server name for the Ping command’s computername parameter, you specify the %i variable. Prefixing the Ping command with the at (@) sign tells the command processor to turn off the command-echoing feature for that command. (For more information about disabling the command-echoing feature, see "Shell Scripting 101, Lesson 1.")If you put all the segments together, the For command for the ping test looks likeFor /d %i in (fileserv1 fileserv2 fileserv3 fileserv4 fileserv5) Do @Ping -n 1 %iThis For /d command produces the same result as the five lines of Ping code.Using the For /f Command If you have many servers to ping, listing all the servers in a set can get cumbersome. A better alternative is to put the server names in an input file. An input file is a file that provides input to a command or script. Typically, input files are text files. Figure 1 shows a sample input file. The For /d command you just created won’t work with the input file that Figure 1 shows. Instead, you need to use a different syntax:For /f ["options"] %variable in (fileset) Do commandThe /f switch lets you use the For command to parse a file’s contents. As the (fileset) parameter shows, you enclose the filename (or filenames—you can include more than one file in a set) in the parentheses. If you use serverlist.txt to provide the server names, the For command for the ping test looks likeFor /f %i in (serverlist.txt) Do @Ping -n 1 %iWhen you run this For /f command, the command processor opens serverlist.txt and reads in each line, which the /f switch parses. The /f switch parses each line into individual pieces, or tokens. By default, the command processor uses spaces or tabs to determine the tokens—that is, it uses spaces or tabs as the delimiter. So, for example, if you have server names that contain spaces (e.g., fileserv alpha, fileserv beta), the For /f command just given you wouldn’t work because the %i variable would contain only a partial server name (i.e., fileserv).Fortunately, the For /f command provides several parsing options, which the "options" parameter in the For /f command syntax represents. The tokens and delims options are the most commonly used parsing options. The tokens option lets you specify the tokens you want to capture. The delims option lets you use other delimiters besides the default spaces and tabs. A fun way to learn about these options is to try the following experiments.

Page 16: January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is

Experimenting with the Tokens Option Open the command-shell window. Run the commandEcho This experiment should help you understand the For command better > C:\testdata.txtto create a file called testdata.txt on your C drive. Next, run the following commands:For /f %i in (C:\testdata.txt) Do Echo %iFor /f "tokens=1" %i in (C:\testdata.txt) Do Echo %iFor /f "tokens=2" %i in (C:\testdata.txt) Do Echo %iFor /f "tokens=3" %i in (C:\testdata.txt) Do Echo %iFigure 2 shows the results. As you can see, you can select any word in the text file by changing the number of the token. If you don’t use the tokens option, the first token is taken by default.You can select all the tokens in a line by using an asterisk (*). Try the commandFor /f "tokens=*" %i in (C:\testdata.txt) Do Echo %i If you want to select the first, third, and fifth tokens, you can use the commandFor /f "tokens=1,2,3,4,5" %i in (C:\testdata.txt) Do Echo %i %k %mYou’re not limited to keeping the tokens in the order in which they appear in the input file. You can, for example, display the tokens in reverse order with the commandFor /f "tokens=1,2,3,4,5,6,7,8,9,10" %i in (C:\testdata.txt) Do Echo %r %q %p %o %n %m %l %k %j %iYou can even display the tokens in a comma-separated format with a command such asFor /f "tokens=1,2,3,4,5,6,7,8,9,10" %i in (C:\testdata.txt)Do Echo %i,%j,%k,%l,%m,%n,%o,%p,%q,%rAs I discussed in "Shell Scripting 101, Lesson 4," you can redirect the For /f command’s output to a file by adding the >> redirection symbol:For /f "tokens=1,2,3,4,5,6,7,8,9,10" %i in (C:\testdata.txt) Do Echo%i,%j,%k,%l,%m,%n,%o,%p,%q,%r>>C:\testreport1.txtExperimenting with the delims Option In the command-shell window, run the command Echo 10,100,55,23 > C:\testdata2.txtto create the file testdata2.txt on your C drive. Now, run the commands For /f "tokens=1,2,3,4" %i in (C:\testdata2.txt) Do Echo %i %j %k %l For /f "tokens=1,2,3,4 delims=," %i in (C:\testdata2.txt) Do Echo %i %j %k %l Figure 3 shows the results of these two commands. If you don’t include the delims option, the command processor uses the default delimiter (i.e., a space, in this case), thereby reading the entire line as one token, which is why the commas appear in the first command’s result. By adding delims=, to the command, the command processor uses a comma as the delimiter, thereby reading each number as a token, which is why the second command’s result shows no commas.In "Shell Scripting 101, Lesson 5," I showed you how to use the Set /a command to perform simple math calculations. You can use the Set /a command in a For /f command to return, then add numbers from an input file. For example, if you run the commandFor /f "tokens=1,2,3,4 delims=," %i in (C:\testdata2.txt) Do Set /A Fred=%i+%j+%k+%l you get the result 188 (10+100+55+23).Explore More Uses As you can see, the For command is versatile—and I’ve only covered the most common uses of the For command. You can further explore the parameters, switches, and options the command offers by running the commandFor /?|More to obtain the Help file.Homework Assignments

1. In a script, use the For /d command to open five instances of Microsoft Internet Explorer (IE) that point to your favorite Web sites. Here’s a hint on the code to launch IE: Use the path to your iexplore.exe program enclosed in quotes, followed by the URL to a favorite Web site (e.g., "C:\program files\plus!\microsoft internet\iexplore.exe" http://www.winscriptingsolutions.com).

2. Put your five favorite URLs in an input file. Modify the script so that it uses the For /f command to parse the input file for the paths used to launch the browser instances.

Figure 1

Page 17: January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is

Figure 2

Figure 3

August 28, 2001   |   Dick Lewis   |   Feature   |   Instant Doc #22289

Page 18: January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is

Shell Scripting 101, Lesson 9

By default, the command interpreter (aka the command processor) reads and executes each line in a script, from top to bottom. When you write scripts, you sometimes need to change the order in which the command interpreter executes the code. In other words, you need to change the flow of the script. You can control a script’s flow with the Goto, Call, and Exit commands. To understand these commands, you first need to be familiar with labels.

Labels A label marks a spot to which you want the command interpreter to jump. After the command interpreter jumps to that spot, it starts executing the code downward again. The label’s syntax is

:Label1where Label1 is the label’s name preceded by a colon (:). You can specify any name, except for EOF (more on this exception later). As I mentioned in "Shell Scripting 101, Lesson 5,", you can embed spaces in the label but you can’t include commas, semicolons, or other separators. Technically, the label can be any length. However, the command interpreter reads only the first eight characters, which can cause problems if you use several labels that have similar long names. For example, if you have the labels :MyLabel01 and :MyLabel02, the command interpreter reads both labels as :MyLabel0, which can cause errors in a script.As the code:Fred

Echo Fred was here.shows, the label needs to be the sole element on the line. In other words, you can’t have commands on the same line as the label. Code such as:Fred Echo Fred was here.causes an error. You can have as many labels as you want in a script. You use labels with the Goto and Call commands.The Goto Command The Goto command moves a script’s flow to the specified label. This command’s syntax isGoto [:]Label1where Label1 is the name of the label to which you want the command interpreter to jump. For example, in the code that Listing 1 shows, the Goto command tells the command interpreter to jump to the :Fred label. Because the script’s flow jumps from the first line to the third line, the command interpreter never executes the Echo command in the second line.In the Goto command’s syntax, you might have noted that the colon is in square brackets. Square brackets denote an optional element, which means preceding the label’s name with a colon is optional (except for EOF, which I’ll discuss shortly) in the Goto command. However, because the colon is mandatory in the actual label, including the colon in any label reference is a good habit to get into.The Call Command As you’ve just seen, the Goto command tells the command interpreter to go from the current location (point A) to another location (point B), then perform point B’s tasks. The command interpreter doesn’t return to point A when it’s finished with those tasks. Like the Goto command, the Call command tells the command interpreter to go from point A to point B, then perform the tasks. However, unlike the Goto command, the Call command tells the command interpreter to return to point A when it’s finished with those tasks.For example, in the code that Listing 2 shows, the Call command tells the command interpreter to jump to the :Fred label and display the message Fred was here. The command interpreter then returns to the point from which it made the jump and displays the message Wilma was here.Another difference between the Call and Goto commands is that you can use the Call command to execute another .bat or .cmd script from within the current script. If you want to call another script, you use the syntaxCall [drive:][path] filename [arguments]where filename is the name of the second script. If the second script isn’t in the same directory as the current script, you need to specify the drive and path along with the filename. In the arguments parameter, you specify any command-line arguments that the second script needs to run.If you want to execute code that lies within the current script (e.g., Listing 2), you use the Call command with a label. In this case, the syntax isCall :Label1 [arguments]where Label1 is the name of the label that marks the location of the code to execute. Note that the colon preceding the label name isn’t in parentheses. Unlike the Goto command, the Call command requires you to precede the label’s name with a colon. Because the code that follows a label can be a subroutine, the Call command syntax includes the arguments parameter. You use this parameter to provide any command-line arguments that a subroutine might need to run.

Page 19: January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is

If you use the Call command to jump to and execute a subroutine, the command interpreter assumes that the subroutine ends at the end of the file (i.e., with the last command in the script). If the subroutine ends elsewhere, you can use an :EOF label to specify the subroutine’s end.The :EOF Label and the Exit Command The :EOF label is a special built-in label that simulates the End of File (EOF). Because :EOF is a built-in label, you can’t use the name EOF for any of your labels.When you use the :EOF label with the Goto command, you can’t leave out the colon. The Goto :EOF command tells the command interpreter to jump to the end of the script. Let’s look at this command in action. Suppose that you want to delete the file fred.txt, but you’re not sure whether the file is on the C or D drive. As Listing 3 shows, you can write code that uses the If Exist command to test whether the file fred.txt is on the C or D drive. (If you’re unfamiliar with the If Exist command, see "Shell Scripting 101, Lesson 6.") If the file is on the C drive, the command interpreter jumps to the :Delthemc label, deletes the file, and jumps to the end of the script. If the file is on the D drive, the command interpreter jumps to the :Delthemd label, deletes the file, and jumps to the end of the script.Listing 4 shows another way in which you can write this code. Instead of using the Goto :EOF command, you can use the Exit command. The Exit command quits that session of the command interpreter. Listing 1 and Listing 2 produce identical results.Homework Assignment1. Use labels to modify Listing 1 in "Shell Scripting 101, Lesson 5". Move the script’s flow to a new label and section of code when the counter reaches values 6 through 10.

Listing 1:: Listing 1. Code That Uses the Goto Command

Goto :FredEcho Wilma was here.:FredEcho Fred was here.

Listing 2:: Listing 2. Code That Uses the Call Command

Call :FredEcho Wilma was here.:FredEcho Fred was here.

Listing 3:: Listing 3. Code That Uses the Goto :EOF Command

If Exist C:\fred.txt Goto :DelthemcIf Exist D:\fred.txt Goto :Delthemd:DelthemcDel C:\fred.txtGoto :EOF:DelthemdDel D:\fred.txt

Page 20: January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is

Goto :EOF

Listing 4:: Listing 4. Code That Uses the Exit Command

If Exist C:\fred.txt Goto :DelthemcIf Exist D:\fred.txt Goto :Delthemd:DelthemcDel C:\fred.txtExit:DelthemdDel D:\fred.txtExit

September 25, 2001   |   Dick Lewis   |   Feature   |   Instant Doc #22582

Shell Scripting 101, Lesson 10

Timing is everything—even in scripts. You can control the timing in your scripts with such commands as Pause, Sleep, Timeout, Waitfor, and Start. Some of these commands are part of the Windows scripting language; others are from utilities in the Microsoft Windows NT Server 4.0 Resource Kit.

The Pause Command You can use the Pause command to stop the execution of scripts. This command displays the message Press any key to continue and stops the script’s execution until the user presses a key. For example, if you run the code

Echo Here is the first line of code.PauseEcho Here is the second line of code.you receive the results that Figure 1 shows.Scriptwriters often use the Pause command to stop a script’s execution so that they can read command output before it scrolls off the screen. However, if a script contains the Pause command, you can’t use Task Scheduler to run that script. (Task Scheduler comes with Microsoft Internet Explorer—IE—4.x and later.) The script will never finish executing because no one is present to press a key to resume the script’s execution. You’ll likely want to use Task Scheduler because it’s easier to use and provides more functionality than the At command and the resource kit’s Winat utility.The Sleep and Timeout Commands Although you can’t use the Pause command with Task Scheduler, you can use the resource kit’s Sleep and Timeout utilities. Both utilities let you pause a script for a specified number of seconds. For example, if you want to use the Sleep utility to pause a script for 5 seconds, you can use the commandSleep 5Putting this command in the codeEcho Here is the first line of code.Sleep 5Echo Here is the second line of code.prompts the command processor to display the message Here is the first line of code, pause for 5 seconds, then automatically continue to the next line and display the message Here is the second line of code.Similarly, you can use the Timeout command to pause a script a specified number of seconds. However, the Timeout command differs from the Sleep command in one important respect: Two events can prompt the script to resume running. You can opt to have the script automatically continue executing after the specified number of seconds has elapsed, or you can manually prompt the script to resume before that time is up by pressing a key on the keyboard. For example, the code

Page 21: January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is

Echo Here is the first line of code.Timeout 10Echo Here is the second line of code.first prompts the command processor to display the message Here is the first line of code. The command processor then pauses until someone presses a key or 10 seconds elapse (whichever comes first), after which it executes the next line of code. Because of this feature, the Timeout utility is ideal for scripts that you plan to execute both manually and as scheduled tasks. The Sleep command is better when you simply need a short delay between two commands or two sections in a script that you plan to run only with Task Scheduler.The Waitfor Command The resource kit’s Waitfor utility is interesting because to use it, you need two machines (typically, a server and a client) in the same domain. The best way to describe how this utility works is with an example. Begin by running the code that Listing 1 shows on the client. On the client’s screen, notice that only the first line of code runs and displays the message Here is the first line of code. Then, on the server, run the commandWaitfor –s freds-signalThis command sends a signal that triggers the client into completing the tasks you programmed in with the code in Listing 1. The –s switch specifies the signal (in this case, freds-signal) that the client waits for. When the client receives this signal, it runs the rest of the lines in Listing 1, one line at a time, until it receives another Waitfor signal. This example involves only one computer receiving the signal. Multiple machines can wait for the same signal.The Waitfor command has a –t switch that lets the client code time-out if the client doesn’t receive the specified signal. If you don’t use the –t switch, the default wait time is forever. As Listing 2 shows, you simply add to the client code the –t switch followed by the number of seconds you want the client to wait. On the server, you run the same Waitfor command you ran previously.The Start Command If you have a task in which you need to start several scripts either sequentially or at the same time, you can use the Start command. The Start command launches a separate command shell window to run a specified command or script.For example, suppose you need to simultaneously launch the four scripts that Listing 3,4,5 and 6 show. Listing 7 contains a master launching script that you can use. By using the Start command, you can launch all four scripts virtually simultaneously. Listing 8 contains a variation of the launching script. In this script, I added the /wait switch to the Start command. This switch prompts the Start command to wait for each script to finish running before launching the next command shell window.Hooked on Scripting This lesson completes my 10-lesson introduction to Windows shell scripting. I hope you’ve enjoyed the lessons and become hooked on scripting.Homework Assignment

1. Find out what the scripts in Listings 3 through 6 are doing. Run the command

Color /?in a command shell window.

2. The Start command offers many parameters and switches. Explore your options by running the command

Start /?in a command shell window.

Figure 1

Page 22: January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is

Listing 1:: Listing 1. The Waitfor Command

Echo Here is the first line of code.Waitfor freds-signalEcho Here is the second line of code.Waitfor freds-signalEcho Here is the third line of code.Waitfor freds-signalEcho Here is the last line of code.Waitfor freds-signalExit

Listing 2:: Listing 2. The Waitfor Command with the -t Switch

Echo Here is the first line of code.Waitfor -t 20 freds-signalEcho Here is the second line of code.Waitfor -t 20 freds-signalEcho Here is the third line of code.Waitfor -t 20 freds-signalEcho Here is the last line of code.Waitfor -t 20 freds-signalExit

Listing 3:: Listing 3. ScriptA.bat

Color 1fPauseExit

Page 23: January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is

Listing 4:: Listing 4. ScriptB.bat

Color 2fPauseExit

Listing 5:: Listing 5. ScriptC.bat

Color 3fPauseExit

Listing 6:: Listing 6. ScriptD.bat

Color 4fPauseExit

Listing 7:: Listing 7. Master Launching Script

Start ScriptA.batStart ScriptB.batStart ScriptC.batStart ScriptD.bat

Listing 8:: Listing 8. Master Launching Script with the /wait Switch

Start /wait ScriptA.batStart /wait ScriptB.batStart /wait ScriptC.batStart /wait ScriptD.bat

Page 24: January 3, 2001 | Dick Lewis | Feature | Instant Doc #16355  · Web viewSet /a Wilma=2*3. If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma. you receive the result Fred is