Showing posts with label Output. Show all posts
Showing posts with label Output. Show all posts

Saturday, 28 June 2014

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.”

Windows Commands for Redirecting Standard Input, Output, and Error

Redirecting Standard Input, Output, and Error

By default, commands take input from the parameters specified when they are called by the command shell and then send their output, including errors, to the standard console window. Sometimes, though, you’ll want to take input from another source or send output to a file or other output device such as a printer. You may also want to redirect errors to a file rather than the console window. You can perform these and other redirection tasks using the techniques introduced in Table 2-2 and discussed in the sections that follow.

Table 2-2: Redirection Techniques for Input, Output, and Errors
Redirection Technique
Description
command1 | command2
Sends the output of the first command to be the input of the second command.
command < [path]filename
Takes command input from the specified file path.
command > [path]filename
Sends output to the named file, creating the file if necessary or overwriting it if it already exists.
command >> [path]filename
Appends output to the named file if it exists or creates the file and then writes to it.
command < [path]filename > [path]filename
Gets command input from the specified file and then sends command output to the named file.
command < [path]filename >> [path]filename
Gets command input from the specified file and then appends command output to the named file.
command 2> [path]filename
Creates the named file and sends any error output to it. If the file exists, it is overwritten.
command 2>&1 filename
Sends error output to the same destination as standard output.

Redirecting Standard Output to Other Commands

Most commands generate output that can be redirected to another command as input. To do this, you use a technique called piping, whereby the output of a command is sent as the input of the next command. Following this, you can see the general syntax for piping is

Command1 | Command2

where the pipe redirects the output of Command1 to the input of Command2. But you can also redirect output more than once, such as

Command1 | Command2 | Command3

The two most common commands that are piped include FIND and MORE. The FIND command searches for strings in files or in text passed to the command as input and then lists the text of matching lines as output. For example, you could obtain a list of all .txt files in the current directory by typing the command

dir | find ".txt "

The MORE command accepts output from other commands as input and then breaks this output into sections which can be viewed one console page at a time. For example, you could page through a log file called Dailylog.txt using the following command:

type c:\working\logs\dailylog.txt | more

Type find /? or more /? at the command line to get a complete list of the syntax for these commands.

Redirecting I/O to and from Files

Another command redirection technique is to get input from a file using the input redirection symbol (<). For example, the following command sorts the contents of the Usernames.txt file and displays the results to the command line:

sort < usernames.txt

Just as you can read input from a file, you can also send output to a file. To do this, you can use > to create or overwrite, or >> to create or append data to a named file. For example, if you want to write the current network status to a file, you could use the command

netstat -a > netstatus.txt

Unfortunately, if there is an existing file in the current directory with the same file name, this command overwrites the file and creates a new one. If you want to append this information to an existing file rather than overwrite an existing file, change the command text to read

netstat -a >> netstatus.txt

The input and output redirection techniques can be combined as well. You could, for example, obtain command-input from a file and then redirect command-output to another file. In this example, a list of user names is obtained from a file and sorted, and then the sorted name list is written to a new file:

sort < usernames.txt > usernames-alphasort.txt

Redirecting Standard Error

By default, errors from commands are written as output on the command line. If you are running unattended batch scripts or utilities, however, you may want to redirect standard error to a file so that errors are tracked. One way to redirect standard error is to tell the command line that errors should go to the same destination as standard output. To do this, type the 2>&1 redirection symbol as shown in this example:

chkdsk /r > diskerrors.txt 2>&1

Here, you send standard output and standard error to a file called Diskerrors.txt. If you want to see only errors, you can redirect only the standard error. In this example, standard output is displayed at the command line and standard error is sent to the file Diskerrors.txt:

chkdsk /r 2> diskerrors.txt

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.