Showing posts with label Create Commands. Show all posts
Showing posts with label Create Commands. Show all posts

Saturday, 28 June 2014

Getting Acquainted with Variables in CMD

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.

Creating Command Line Scripts in Windows

Creating Command Line Scripts

Command line scripts are text files containing the commands you want to execute. These are the same commands you would normally type into the Windows command shell. However, rather than enter the commands each time you want to use them, you create a script to store the commands for easy execution.
Because scripts contain standard text characters, you can create and edit scripts using a standard text editor, such as Notepad. When you enter commands, be sure to place each command or group of commands that should be executed together on a new line. This ensures proper execution of the commands. When you have finished creating a command-line script, save the script file using the .bat or .cmd extension. Both extensions work with command-line scripts in the same way. For example, if you wanted to create a script to display the system name, Windows version and IP configuration, you could enter these three commands into a file called SysInfo.bat or SysInfo.cmd:

hostname
ver
ipconfig -all
Once you save the script, you can execute it as if it were a Windows utility; simply type the name of the script in a command shell and press Enter. When you do this, the command shell reads the script file and executes its commands one by one. It stops executing the script when it reaches the end of the file or reads an EXIT command. For the example script, the command line would display output similar to Listing 3-1.
Listing 3-1: Output of Sample Script
Start example
C:\>hostname
mailer1
C:\>ver
Microsoft Windows [Version 5.2.3790]
C:\>ipconfig -all
Windows IP Configuration
Host Name . . . . . . . . . . . . : mailer1
Primary Dns Suffix . . . . . . . : adatum.com
Node Type . . . . . . . . . . . . : Unknown
IP Routing Enabled. . . . . . . . : No
WINS Proxy Enabled. . . . . . . . : No
DNS Suffix Search List. . . . . . : adatum.com
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix . :
Description . . . . . . . . . . . : Intel(R) PRO/100 VE Network
Connection
Physical Address. . . . . . . . . : X0-EF-D7-AB-E2-1E
DHCP Enabled. . . . . . . . . . . : No
IP Address. . . . . . . . . . . . : 192.168.10.50
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 192.168.10.1
DNS Servers . . . . . . . . . . . : 192.168.10.155
End example
If you examine the listing, you’ll see that the command prompt and the actual commands are displayed as well as the output of the commands themselves. The reason for this is that the command shell does some extra work behind the scenes while executing scripts in the default processing mode. First, the command shell displays the command prompt. Next, it reads a line from the script, displays it, and then interprets it. If the command shell reaches the end of the file or reads an EXIT command, execution stops. Otherwise, the command shell starts this process all over again by displaying the prompt and preparing to read the next line in the script.
Although the default processing mode with command echoing on can be useful for troubleshooting problems in scripts, you probably don’t want to use this display mode with scripts you’ll use regularly. Fortunately, you can change the default behavior by turning command echo off, as I’ll show you later in the chapter in the section titled “Managing Text Display and Command Echoing.”

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.