Showing posts with label Windows CMD. Show all posts
Showing posts with label Windows CMD. Show all posts

Saturday, 28 June 2014

Getting Acquainted with Variables

Getting Acquainted with Variables

In command-line scripting, what we commonly call variables are more properly called environment variables. Environment variables can come from many sources. Some variables are built into the operating system or derived from the system hardware during startup. These variables, called built-in system variables, are available to all Windows processes regardless of whether anyone is logged on interactively. System variables can also come from the Windows Registry. Other variables are set during logon and are called built-in user variables. The built-in user variables available are the same, no matter who is logged on to the computer. As you might expect, they are valid only during an actual logon session, that is, when a user is logged on.
You can see a listing of all the variables known in the current instance of the command shell by typing set at the prompt. In addition to the normal system and user variables, you can create variables whenever Windows is running, which is exactly what you’ll do when you program in the command shell. You define variables for the current instance of the command shell using the SET command and the following syntax:
set variable_name=variable_value
such as
set working=C:\Work\Data
set value=5
set string="Hello World"
Some variables, including system and user environment variables, have special meaning in the command shell. These variables include path, computername, homedrive, and many other important environment variables. One environment variable that you should learn more about is errorlevel, which tracks the exit code of the most recently used command. If the command executes normally, the error level is zero (0). If an error occurs while executing the command, the error level is set to an appropriate nonzero value. Error values include
  • 1  Indicates a general error
  • 2  Indicates an execution error, meaning the command failed to execute properly
  • 2  Indicates a math error, such as when you create a number that is too large for the command shell to handle
You can work with the errorlevel variable in several ways. You can check for a specific error condition, such as
if "%ERRORLEVEL%"=="2" echo "An error occurred!"
Or, you can use the following special syntax and check for a condition equal to or greater than the specified exit code:
if errorlevel 2 echo "An error occurred!"
Note 
You’ll see more on errorlevel and if statements later in the chapter in the section titled “Using Conditional Statements.”
When you are finished working with variables, it’s good form to dispose of them. You do this to free memory used by the variable and prevent problems or unexpected results if you accidentally refer to the variable in the future. To clear out a variable, you simply set the variable equal to nothing, such as
set working=

Now the variable is cleared out of memory and is no longer available.

Common Statements and Commands for Scripts in Windows CMD

Common Statements and Commands for Scripts

So far in this book, I’ve discussed commands but haven’t really introduced what a statement is. While these terms are often used interchangeably, the term statement technically refers to the keyword for a command, such as the rem statement, but it can also refer to a line of code that includes all the command text on that line. In some programming languages, such as Java, each statement must be terminated with a specific character. With Java, the terminator is a semicolon. The command line doesn’t look for a specific terminator, other than the end of the line, which is assumed when the command interpreter reads any of the following:
  • Line break (such as when you press Shift+Enter)
  • Carriage return and line break (such as when you press Enter)
  • End-of-file marker
Now that we’ve discussed how to create scripts, let’s look at common statements and commands you’ll use in scripts, including
  • Cls  Clears the console window and resets the screen buffer
  • Rem  Creates comments in scripts
  • Echo  Displays messages at the command line and turns command echoing on or off
  • @  Controls command echo on a line-by-line basis
  • Title  Sets the title for the command shell window
  • Color  Sets the text and background colors used in the command shell window

Clearing the Command-Shell Window

Clearing the command-shell window before writing script output is usually a good idea. You clear the command-shell window using the CLS command. Why not try it? At the command line, type cls and press Enter. The console window clears and the cursor is positioned in the top left corner of the window. All the text in the screen buffer is cleared as well.
You could add the CLS command to the sample script listed previously, as shown in this example:
cls
hostname
ver
ipconfig -all

Adding Comments to Scripts

You use the rem statement to add comments to your scripts. Every script you create should have comments detailing
  • When the script was created and last modified
  • Who created the script
  • What the script is used for
  • How to contact the script creator
  • Whether and where script output is stored
Not only are the answers to these Who, What, How, Where, and When questions important for ensuring that the scripts you create can be used by other administrators, they can also help you remember what a particular script does, especially if weeks or months have passed since you last worked with the script. An example of a script that uses comments to answer these questions is shown as Listing 3-2.

Listing 3-2: Updated Sample Script with Comments
Start example
rem ************************
rem Script: SystemInfo.bat
rem Creation Date: 2/2/2004
rem Last Modified: 3/15/2004
rem Author: William R. Stanek
rem E-mail: williamstanek@aol.com
rem ************************
rem Description: Displays system configuration information
rem including system name, IP configuration
rem and Windows version.
rem ************************
rem Files: Stores output in c:\current-sys.txt.
rem ************************
hostname > c:\current-sys.txt
ver >> c:\current-sys.txt
ipconfig -all >> c:\current-sys.txt
End example
Later in this chapter, in the section titled “Passing Arguments to Scripts,” I’ll show you how to use your comments as automated help documentation. Before we get to that, however, keep in mind that rem statements can also be used to
  • Insert explanatory text within scripts, such as documentation on how a procedure works.
  • Prevent a command from executing. On the command line, add rem before the command to comment it out.
  • Hide part of a line from interpretation. Add rem within a line to block interpretation of everything that follows the rem statement.

Managing Text Display and Command Echoing

The echo command has two purposes. You use the ECHO command to write text to the output, which can be the command shell or a text file. You also use the ECHO command to turn command echoing on or off. Normally, when you execute commands in a script, the commands as well as the resulting output of the command are displayed in the console window. This is called command echoing.
To use the ECHO command to display text, enter echo followed by the text to display, such as
echo The system host name is:
hostname
To use ECHO to control command echoing, type echo off or echo on as appropriate, such as
echo off
echo The system host name is:
hostname
Use output redirection to send output to a file rather than the command shell, as follows:
echo off
echo The system host name is: > current.txt
hostname >> current.txt
To experiment with suppressing command echoing, start a command shell, type echo off, and then enter other commands. You’ll find that the command prompt is no longer displayed. Instead, you see only what you type into the console window and the resulting output from the commands you’ve entered. In scripts, the ECHO OFF command turns off command echoing as well as the command prompt. By adding the command ECHO OFF to your scripts, you keep the command-shell window or the output file from getting cluttered with commands when all you care about is the output from those commands.
Tip 
By the way, if you want to determine whether command echoing is enabled or disabled, type the ECHO command by itself. Give it a try. If command echoing is on, you’ll see the message Echo Is On. Otherwise, you’ll see the message Echo Is Off. Experiment with the ECHO OFF command in your scripts and you may detect a bit of a problem here. If the ECHO OFF command turns off command echoing, how do you prevent the ECHO OFF command itself from echoing? Don’t worry; that’s discussed in the next section.
Real World 
One question that other command-line programmers frequently ask me is, How do you get a blank line to echo in the command shell? You might think that putting the ECHO command on a line by itself would do the job, but it doesn’t. Typing echo on a line by itself displays the status of command echoing as mentioned in the previous tip. Typing echo followed by a space doesn’t work either, because the Windows command line treats spaces (in this situation) as meaningless and you get the same results as typing echo followed by nothing at all. To get ECHO to display a blank line, you must enter echo. (Note that there is no space between the period and the ECHO command.)

Fine-Tuning Command Echo with @

The @ command prevents commands from echoing to the output on a line-by- line basis and you can think of it as a line-specific echo off statement. You could use @ to turn off command echoing like this:
@echo The system host name is:
@hostname
Using @, the output that shows the command prompt and commands like this:
C:\>echo The system host name is:
The system host name is:
C:\>hostname
mailer1
becomes
The system host name is:
mailer1
But the real value of @ is that it allows you to tell the command shell not to display the command prompt or ECHO OFF command, and thereby ensures that the only output of your scripts is the output of the commands you enter. Here is an example of a script that uses @ to hide the ECHO OFF command so that it isn’t displayed in the output:
@echo off
echo The system host name is:
hostname
The output from this script is
The system host name is:
mailer1
Tip 
I recommend using @echo off at the beginning of all your command-line scripts. By the way, if you start a command shell and type @echo off, you can turn off the display of the command prompt as well.

Setting the Console Window Title and Colors

If you’re going to take the time to write a script, you might as well add a few special features to jazz it up. Some of the basic techniques that I’ve already discussed are using the ECHO OFF command and clearing the console window before you write output. You may also want to set a title for the window or change the colors the window uses.
The title bar for the command shell is located at the top of the console window. Normally, this title bar displays “Command Prompt” or the file path to the command shell. You can customize the title using the TITLE command. This command works much like the ECHO command in that it displays whatever text follows it on the console’s title bar. For example, if you wanted to set the title of the current console to “System Information,” you could do this by entering the following at the command line:
title System Information
You can not only use the TITLE command to show the name of the script that is running; you can also use TITLE to show the progress of the script as it executes, such as
rem add blocks of work commands
title Gathering Information
rem add blocks of logging commands
title Logging System Information
By default, the console window displays white text on a black background. As you learned in Chapter 1, “Overview of the Windows Command Line,” you can modify this behavior using the Colors tab of the Command Prompt Properties dialog box. You can also set console colors by using the COLOR command. You do this by passing the command a 2-digit hexadecimal code. The first digit corresponds to the background color and the second digit corresponds to the text color, such as
color 21
which sets the text to blue and the background color to green.
The color codes you can use with the COLOR command are shown in Table 3-1. Keep in mind that you can’t set the text and background colors to the same value. If you try to do this, the color doesn’t change. Additionally, you can restore the default colors at any time by using the COLOR command without any arguments, such as
color
Table 3-1: Color Codes for the Command Shell Window
Code
Color
Code
Color
0
Black
8
Gray
1
Blue
9
Bright Blue
2
Green
A
Bright Green
3
Aqua
B
Bright Aqua
4
Red
C
Bright Red
5
Purple
D
Bright Purple
6
Yellow
E
Bright Yellow
7
White
F
Bright White

Managing Command Shell

Managing Command Shell Startup

When you previously worked with the command line, you probably started it by clicking Start, pointing to Programs or All Programs, Accessories, and then choosing Command Prompt. Another way to start a command line is to use the Run dialog box or type cmd in an open command-shell window. These techniques enable you to pass arguments to the command line, including switches that control how the command line works as well as parameters that execute additional commands. For example, you can start the command shell in quiet mode (meaning command echo is turned off) by using the startup command cmd /q and if you wanted the command shell to execute a command and then terminate, you could type cmd /c followed by the command text enclosed in quotation marks. The following example starts a command shell, sends the output of ipconfig to a file, and then exits the command shell:

cmd /c "ipconfig > c:\ipconfig.txt"

Table 2-1 summarizes the key parameters for the Windows command shell (Cmd.exe). Note that several command-line parameters are set by default. Because of this, the command line normally uses standard ANSI character codes for command output, as opposed to Unicode character codes, and enables command extensions that add features to most built-in commands.

Table 2-1: Essential Parameters for the Command Line
Parameter
Description
/C
Executes the command specified and then exits the command shell.
/K
Executes the command specified and then remains in interactive mode.
/A
Command output to files (or pipes) is set to ANSI format (default).
/U
Command output to files (or pipes) is set to Unicode.
/U
Turns on quiet mode, meaning command echo is off. By default, command echo is on.
/T:FG
Sets the foreground and background colors for the console window.
/E:ON
Enables command extensions, which is the default.
/E:OFF
Disables command extensions.


Note

Some parameters cannot be used with other switches. For example, you can’t enable both Unicode and ANSI character codes. If you use both /A and /U, or /E:ON and /E:OFF, the command line applies the last option you passed on the command line.
Sometimes you may want to use different environment settings or parameters for a command line and then go back to your original settings without exiting the console window. To do this, you can use a technique called nesting. With nesting, you start a command line within a command line and the nested command line inherits its environment settings from the current command line. You can then modify the environment as necessary and execute commands and scripts using those settings. When you type exit to end the nested command- line instance, you return to the previous command line and the previous environment settings are restored.


Tip 
As you set out to work with the command shell, keep in mind that some characters have special meanings and that whenever the command shell encounters one of these characters, it attempts to carry out the special procedure associated with that character. Special characters include < > ( ) & | @ ^. If you want to use a special character as a regular character, you must escape the special character for the command shell to look at it literally, without invoking the special procedures with which it is associated. The escape character is the caret (^), which is the character above the 6 key on a standard keyboard, and is placed to immediately precede the special character.