`
chelsea
  • 浏览: 117879 次
  • 来自: ...
社区版块
存档分类
最新评论

Programming Windows Batch Script

 
阅读更多

1. Quick Edit Mode

To copy and paste MS-DOS text using the mouse

  1. <noloc></noloc>Open the Command Prompt window.
  2. Right-click the title bar of the command prompt window, and then click Properties.
  3. On the Options tab, under Edit Options, select the QuickEdit Mode check box if it isn't already selected, and then click OK.
  4. In the Apply Properties To Shortcut dialog box, click either of the following:
    • Apply properties to current window only to use QuickEdit mode in the current window.
    • Modify shortcut that started this window to apply QuickEdit mode every time you start the <nobr>MS-DOS</nobr>-based program.
    Click OK.
  5. Click and drag the mouse pointer over the text you want to copy in the command prompt window.
  6. Position the cursor where you want the text to be inserted, and then do either of the following:
    • In an MS-DOS-based program, right-click the title bar, click Edit, and then click Paste.
    • In a <noloc></noloc>Windows-based program, click the Edit menu, and then click Paste.

2. Using command redirection operators

You can use redirection operators to redirect command input and output streams from the default locations to different locations. The input or output stream location is referred to as a handle.

The following table lists operators that you can use to redirect command input and output streams.

Redirection operator Description
> Writes the command output to a file or a device, such as a printer, instead of the Command Prompt window.
< Reads the command input from a file, instead of reading input from the keyboard.
>> Appends the command output to the end of a file without deleting the information that is already in the file.
>& Writes the output from one handle to the input of another handle.
<& Reads the input from one handle and writes it to the output of another handle.
| Reads the output from one command and writes it to the input of another command. Also known as a pipe.

By default, you send the command input (that is, the STDIN handle) from your keyboard to Cmd.exe, and then Cmd.exe sends the command output (that is, the STDOUT handle) to the Command Prompt window.

The following table lists the available handles.

Handle Numeric equivalent of handle Description
STDIN 0 Keyboard input
STDOUT 1 Output to the Command Prompt window
STDERR 2 Error output to the Command Prompt window
UNDEFINED 3-9 These handles are defined individually by the application and are specific to each tool.

The numbers zero through nine (that is, 0-9) represent the first 10 handles. You can use Cmd.exe to run a program and redirect any of the first 10 handles for the program. To specify which handle you want to use, type the number of the handle before the redirection operator. If you do not define a handle, the default < redirection input operator is zero (0) and the default > redirection output operator is one (1). After you type the < or > operator, you must specify where you want to read or write the data. You can specify a file name or another existing handle.

To specify redirection to existing handles, use the ampersand (&) character followed by the handle number that you want to redirect (that is, &handle#). For example, the following command redirects handle 2 (that is, STDERR) into handle 1 (that is, STDOUT):

1<&2

Duplicating handles

The & redirection operator duplicates output or input from one specified handle to another specified handle. For example, to send dir output to File.txt and send the error output to File.txt, type:

dir>c:/file.txt 2>&1

When you duplicate a handle, you duplicate all characteristics of the original occurrence of the handle. For example, if a handle has write-only access, all duplicates of that handle have write-only access. You cannot duplicate a handle with read-only access into a handle with write-only access.

Redirecting command input (<)

To redirect command input from the keyboard to a file or device, use the < operator. For example, to get the command input for the sort command from File.txt:

sort<file.txt

The contents of File.txt appear in the Command Prompt window as an alphabetized list.

The < operator opens the specified file name with read-only access. As a result, you cannot write to the file when you use this operator. For example, if you start a program with <&2, all attempts to read handle 0 fail because handle 2 is initially opened with write-only access.

Note

  • Zero is the default handle for the < redirection input operator.

Redirecting command output (>)

Almost all commands send output to your Command Prompt window. Even commands that send output to a drive or printer display messages and prompts in the Command Prompt window.

To redirect command output from the Command Prompt window to a file or device, use the > operator. You can use this operator with most commands. For example, to redirect dir output to Dirlist.txt:

dir>dirlist.txt

If Dirlist.txt does not exist, Cmd.exe creates it. If Dirlist.txt exists, Cmd.exe replaces the information in the file with the output from the dir command.

To run the netsh routing dump command and then send the command output to Route.cfg, type:

netsh routing dump>c:/route.cfg

The > operator opens the specified file with write-only access. As a result, you cannot read the file when you use this operator. For example, if you start a program with redirection >&0, all attempts to write handle 1 fail because handle 0 is initially opened with read-only access.

Note

  • One is the default handle for the > redirection output operator.

Using the <& operator to redirect input and duplicate

To use the redirection input operator <&, the file you specify must already exist. If the input file exists, Cmd.exe opens it as read-only and sends the characters contained in the file as input to the command as if they were input from the keyboard. If you specify a handle, Cmd.exe duplicates the handle you specify onto the existing handle in the system.

For example, to open File.txt as input read to handle 0 (that is, STDIN), type:

<file.txt

To open File.txt, sort the contents and then send the output to the Command Prompt window (that is, STDOUT), type:

sort<file.txt

To find File.txt, and then redirect handle 1 (that is, STDOUT) and handle 2 (that is, STDERR) to the Search.txt, type:

findfile file.txt>search.txt 2<&1

To duplicate a user-defined handle 3 as input read to handle 0 (that is, STDIN), type:

<&3

Using the >& operator to redirect output and duplicate

If you redirect output to a file and you specify an existing file name, Cmd.exe opens the file as write-only and overwrites the file's contents. If you specify a handle, Cmd.exe duplicates the file onto the existing handle.

To duplicate a user-defined handle 3 into handle 1, type:

>&3

To redirect all of the output, including handle 2 (that is, STDERR), from the ipconfig command to handle 1 (that is, STDOUT), and then redirect the ouput to Output.log, type:

ipconfig.exe>>output.log 2>&1

Using the >> redirection operator to append output

To add the output from a command to the end of a file without losing any of the information already in the file, use two consecutive greater than signs (that is, >>). For example, the following command appends the directory list produced by the dir command to the Dirlist.txt file:

dir>>dirlist.txt

To append the output of the netstat command to the end of Tcpinfo.txt, type:

netstat>>tcpinfo.txt

Using the pipe operator (|)

The pipe operator (|) takes the output (by default, STDOUT) of one command and directs it into the input (by default, STDIN) of another command. For example, the following command sorts a directory:

dir | sort

In this example, both commands start simultaneously, but then the sort command pauses until it receives the dir command's output. The sort command uses the dir command's output as its input, and then sends its output to handle 1 (that is, STDOUT).

Combining commands with redirection operators

You can create custom commands by combining filter commands with other commands and file names. For example, you can use the following command to store the names of files that contain the string "LOG":

<noloc></noloc>dir /b | find "LOG" > loglist.txt

The dir command's output is sent through the find filter command. File names that contain the string "LOG" are stored as a list of file names (for example, NetshConfig.log, Logdat.svd, and Mylog.bat) in the Loglist.txt file.

To use more than one filter in the same command, separate the filters with a pipe (|). For example, the following command searches every directory on drive C:, finds the file names that include the string "Log", and then displays them in one Command Prompt window at a time:

<noloc></noloc>dir c:/ /s /b | find "LOG" | more

By using a pipe (|), you direct Cmd.exe to send the dir command output through the find filter command. The find command selects only file names that contain the string "LOG." The more command displays the file names that are selected by the find command, one Command Prompt window at a time. For more information about filter commands, see Using filters.

3. If

Performs conditional processing in batch programs.

Syntax

<nobr><b>if</b> [<b>not</b>] <b>errorlevel</b> <i>number</i> <i>command</i> [<b>else</b> <i>expression</i>]</nobr>

<nobr><b>if</b> [<b>not</b>] <i>string1</i><b>==</b><i>string2</i> <i>command</i> [<b>else</b> <i>expression</i>]</nobr>

<nobr><b>if</b> [<b>not</b>] <b>exist </b><i>FileName</i> <i>command</i> [<b>else</b> <i>expression</i>]</nobr>

If command extensions are enabled, use the following syntax:

<nobr><b>if</b> [<b>/i</b>] <i>string1</i> <i>CompareOp</i> <i>string2</i> <i>command</i> [<b>else</b> <i>expression</i>]</nobr>

<nobr><b>if</b> <b>cmdextversion</b> <i>number</i> <i>command</i> [<b>else</b> <i>expression</i>]</nobr>

<nobr><b>if</b> <b>defined</b> <i>variable</i> <i>command</i> [<b>else</b> <i>expression</i>]</nobr>

Parameters

not
Specifies that the command should be carried out only if the condition is false.
errorlevel number
Specifies a true condition only if the previous program run by Cmd.exe returned an exit code equal to or greater than number.
command
Specifies the command that should be carried out if the preceding condition is met.
string1==string2
Specifies a true condition only if string1 and string2 are the same. These values can be literal strings or batch variables (for example, %1). You do not need to use quotation marks around literal strings.
exist FileName
Specifies a true condition if FileName exists.
CompareOp
Specifies a three-letter comparison operator. The following table lists valid values for CompareOp. Operator Description
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
/i
Forces string comparisons to ignore case. You can use /i on the string1==string2 form of if. These comparisons are generic, in that if both string1 and string2 are both comprised of all numeric digits, the strings are converted to numbers and a numeric comparison is performed.
cmdextversion number
Specifies a true condition only if the internal version number associated with the Command Extensions feature of Cmd.exe is equal to or greater than number. The first version is 1. It is incremented by one when significant enhancements are added to the command extensions. The cmdextversion conditional is never true when command extensions are disabled (by default, command extensions are enabled).
defined variable
Specifies a true condition if variable is defined.
expression
Specifies a command-line command and any parameters to be passed to the command in an else clause.
/?
Displays help at the command prompt.

Remarks

  • If the condition specified in an if command is true, the command that follows the condition is carried out. If the condition is false, the command in the if clause is ignored, and executes any command in the else clause, if one has been specified.
  • When a program stops, it returns an exit code. You can use exit codes as conditions by using the errorlevel parameter.
  • Using defined variable

    If you use defined variable, the following three variables are added: %errorlevel%, %cmdcmdline%, and %cmdextversion%.

    %errorlevel% expands into a string representation of the current value of errorlevel, provided that there is not already an environment variable with the name ERRORLEVEL, in which case you get the ERRORLEVEL value instead. The following example illustrates how you can use errorlevel after running a batch program:

    goto answer%errorlevel%
    :answer0
    echo Program had return code 0
    :answer1
    echo Program had return code 1
    goto end
    :end
    echo done!

    You can also use the CompareOp comparison operators as follows:

    if %errorlevel% LEQ 1 goto okay

    %cmdcmdline% expands into the original command line passed to Cmd.exe prior to any processing by Cmd.exe, provided that there is not already an environment variable with the name cmdcmdline, in which case you get the cmdcmdline value instead.

    %cmdextversion% expands into the a string representation of the current value of cmdextversion, provided that there is not already an environment variable with the name CMDEXTVERSION, in which case you get the CMDEXTVERSION value instead.

  • Using the else clause

    You must use the else clause on the same line as the command after the if. For example:

    IF EXIST filename. (
    del filename.
    ) ELSE (
    echo filename. missing.
    )

    The following code does not work because you must terminate the del command by a new line:

    IF EXIST filename. del filename. ELSE echo filename. missing

    The following code does not work because you must use the else clause on the same line as the end of the if command:

    IF EXIST filename. del filename.
    ELSE echo filename. missing

    If you want to format it all on a single line, use the following form of the original statement:

    IF EXIST filename. (del filename.) ELSE echo filename. missing

Examples

If the file Product.dat cannot be found, the following message appears:

if not exist product.dat echo Can't find data file

If an error occurs during the formatting of the disk in drive A, the following example displays an error message:

:begin
@echo off
format a: /s
if not errorlevel 1 goto end
echo An error occurred during formatting.
:end
echo End of batch program.

If no error occurs, the error message does not appear.

You cannot use the if command to test directly for a directory, but the null (NUL) device does exist in every directory. As a result, you can test for the null device to determine whether a directory exists. The following example tests for the existence of a directory:

if exist c:mydir/nul goto process

<noloc></noloc>

4. For

Runs a specified command for each file in a set of files.

Syntax

<nobr><b>for</b> {<b>%</b><i>variable</i>|<b>%%</b><i>variable</i>} <b>in (</b><i>set</i><b>)</b> <b>do </b><i>command</i> [<i> CommandLineOptions</i>]</nobr>

Parameters

{%variable|%%variable}
Required. Represents a replaceable parameter. Use %variable to carry out for from the command prompt. Use %%variable to carry out the for command within a batch file. Variables are case-sensitive and must be represented with an alpha value, such as %A, %B, or %C.
(set)
Required. Specifies one or more files, directories, range of values, or text strings that you want to process with the specified command. The parentheses are required.
command
Required. Specifies the command that you want to carry out on each file, directory, range of values, or text string included in the specified (set).
CommandLineOptions
Specifies any command-line options that you want to use with the specified command.
/?
Displays help at the command prompt.

Remarks

  • Using for

    You can use the for command within a batch file or directly from the command prompt.

  • Using batch parameters

    The following attributes apply to the for command:

    • The for command replaces %variable or %%variable with each text string in the specified set until the command processes all of the files.
    • For variable names are case-sensitive, global, and no more than 52 total can be active at any one time.
    • To avoid confusion with the batch parameters %0 through %9, you can use any character for variable except the numerals 0 through 9. For simple batch files, a single character such as %%f works.
    • You can use multiple values for variable in complex batch files to distinguish different replaceable variables.
  • Specifying a group of files

    The set parameter can represent a single group of files or several groups of files. You can use wildcards (that is, * and ?) to specify a file set. The following are valid file sets:

    (*.doc)

    (*.doc *.txt *.me)

    (jan*.doc jan*.rpt feb*.doc feb*.rpt)

    (ar??1991.* ap??1991.*)

    When you use the for command, the first value in set replaces %variable or %%variable, and then the specified command processes this value. This continues until all of the files (or groups of files) that correspond to the set value are processed.

  • Using the in and do keywords

    In and do are not parameters, but you must use them with for. If you omit either of these keywords, an error message appears.

  • Using additional forms of for

    If command extensions are enabled (that is, the default), the following additional forms of for are supported:

    • Directories only

      If set contains wildcards (* and ?), the specified command executes for each directory (instead of a set of files in a specified directory) that matches set. The syntax is:

      for /D {%% | %}variable in (set) do command [CommandLineOptions]

    • Recursive

      Walks the directory tree rooted at [Drive:]Path, executing the for statement in each directory of the tree. If no directory is specified after /R, the current directory is assumed. If set is just a single period (.), it only enumerates the directory tree. The syntax is:

      for /R [[Drive :]Path] {%% | %}variable in (set) do command [CommandLineOptions]

    • Iterating a range of values

      Use an iterative variable to set the starting value (start#) and then step through a set range of values until the value exceeds the set ending value (end#). /L will execute the iterative by comparing start# with end#. If start# is less than end# the command will execute. When the iterative variable exceeds end# the command shell exists the loop. You can also use a negative step# to step through a range in decreasing values. For example, (1,1,5) generates the sequence 1 2 3 4 5 and (5,-1,1) generates the sequence (5 4 3 2 1). The syntax is:

      for /L {%% | %}variable in (start#,step#,end#) do command [CommandLineOptions]

    • Iterating and file parsing

      Use file parsing to process command output, strings and file content. Use iterative variables to define the content or strings you want to examine and use the various ParsingKeywords options to further modify the parsing. Use the ParsingKeywords token option to specify which tokens should be passed as iterator variables. Note that when used without the token option, /F will only examine the first token.

      File parsing consists of reading the output, string or file content, breaking it up into individual lines of text and then parsing each line into zero or more tokens. The for loop is then called with the iterator variable value set to the token. By default, /F passes the first blank separated token from each line of each file. Blank lines are skipped. The different syntaxes are:

      for /F ["ParsingKeywords"] {%% | %}variable in (filenameset) do command [CommandLineOptions]

      for /F ["ParsingKeywords"] {%% | %}variable in ("LiteralString") do command [CommandLineOptions]

      for /F ["ParsingKeywords"] {%% | %}variable in ('command') do command [CommandLineOptions]

      The filenameset argument specifies one or more file names. Each file is opened, read and processed before going on to the next file in filenameset. To override the default parsing behavior, specify "ParsingKeywords". This is a quoted string that contains one or more keywords to specify different parsing options.

      If you use the usebackq option, use one of the following syntaxes:

      for /F ["usebackqParsingKeywords"] {%% | %}variable in ("filenameset") do command [CommandLineOptions]

      for /F ["usebackqParsingKeywords"] {%% | %}variable in ('LiteralString') do command [CommandLineOptions]

      for /F ["usebackqParsingKeywords"] {%% | %}variable in (`command`) do command [CommandLineOptions]

      The following table lists the parsing keywords that you can use for ParsingKeywords.

      Keyword Description
      eol=c Specifies an end of line character (just one character).
      skip=n Specifies the number of lines to skip at the beginning of the file.
      delims=xxx Specifies a delimiter set. This replaces the default delimiter set of space and tab.
      <nobr>tokens=x,y,m-n</nobr> Specifies which tokens from each line are to be passed to the for body for each iteration. As a result, additional variable names are allocated. The m-n form is a range, specifying the mth through the nth tokens. If the last character in the tokens= string is an asterisk (*), an additional variable is allocated and receives the remaining text on the line after the last token that is parsed.
      usebackq Specifies that you can use quotation marks to quote file names in filenameset, a back quoted string is executed as a command, and a single quoted string is a literal string command.
    • Variable substitution

      Substitution modifiers for for variable references have been enhanced. The following table lists optional syntax (for any variable I).

      <nobr>Variable with modifier</nobr> Description
      %~I Expands %I which removes any surrounding quotation marks ("").
      %~fI Expands %I to a fully qualified path name.
      %~dI Expands %I to a drive letter only.
      %~pI Expands %I to a path only.
      %~nI Expands %I to a file name only.
      %~xI Expands %I to a file extension only.
      %~sI Expands path to contain short names only.
      %~aI Expands %I to the file attributes of file.
      %~tI Expands %I to the date and time of file.
      %~zI Expands %I to the size of file.
      %~$PATH:I Searches the directories listed in the PATH environment variable and expands %I to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, this modifier expands to the empty string.

      The following table lists modifier combinations that you can use to get compound results.

      <nobr>Variable with combined modifiers</nobr> Description
      %~dpI Expands %I to a drive letter and path only.
      %~nxI Expands %I to a file name and extension only.
      %~fsI Expands %I to a full path name with short names only.
      %~dp$PATH:I Searches the directories listed in the PATH environment variable for %I and expands to the drive letter and path of the first one found.
      %~ftzaI Expands %I to an output line that is like dir.

      In the above examples, you can replace %I and PATH by other valid values. A valid for variable name terminates the <nobr>%~ syntax</nobr>.

      By use uppercase variable names such as %I, you can make your code more readable and avoid confusion with the modifiers, which are not case-sensitive.

  • Parsing a string

    You can use the for /F parsing logic on an immediate string, by wrapping the filenameset between the parentheses in single quotation marks (that is, 'filenameset'). Filenameset is treated as a single line of input from a file, and then it is parsed.

  • Parsing output

    You can use the for /F command to parse the output of a command by making the filenameset between the parenthesis a back quoted string. It is treated as a command line, which is passed to a child Cmd.exe and the output is captured into memory and parsed as if it were a file.

Examples

To use for in a batch file, use the following syntax:

for %%variable in (set) do command [CommandLineOptions]

To display the contents of all the files in the current directory that have the extension .doc or .txt using the replaceable variable %f, type:

for %f in (*.doc *.txt) do type %f

In the preceding example, each file that has the .doc or .txt extension in the current directory is substituted for the %f variable until the contents of every file are displayed. To use this command in a batch file, replace every occurrence of %f with %%f. Otherwise, the variable is ignored and an error message is displayed.

To parse a file, ignoring commented lines, type:

for /F "eol=; tokens=2,3* delims=," %i in (myfile.txt) do @echo %i %j %k

This command parses each line in Myfile.txt, ignoring lines that begin with a semicolon and passing the second and third token from each line to the FOR body (tokens are delimited by commas or spaces). The body of the FOR statement references %i to get the second token, %j to get the third token, and %k to get all of the remaining tokens. If the file names that you supply contain spaces, use quotation marks around the text (for example, "FileName"). To use quotation marks, you must use usebackq. Otherwise, the quotation marks are interpreted as defining a literal string to parse.

%i is explicitly declared in the FOR statement, and %j and %k are implicitly declared by using tokens=. You can specify up to 26 tokens using tokens=, provided that it does not cause an attempt to declare a variable higher than the letter 'z' or 'Z'.

To parse the output of a command by placing filenameset between the parentheses, type:

for /F "usebackq delims==" %i IN (`set`) DO @echo %i

This example enumerates the environment variable names in the current environment.

<noloc></noloc>

5. Setlocal/EndLocal

Starts localization of environment variables in a batch file. Localization continues until a matching endlocal command is encountered or the end of the batch file is reached.

Syntax

<nobr><b>setlocal</b> {<b>enableextension</b> | <b>disableextensions</b>} <wbr></wbr>{<b>enabledelayedexpansion</b> | <b>disabledelayedexpansion</b>}<wbr></wbr></nobr>

Arguments

enableextension
Enables the command extensions until the matching endlocal command is encountered, regardless of the setting prior to the setlocal command.
disableextensions
Disables the command extensions until the matching endlocal command is encountered, regardless of the setting prior to the setlocal command.
enabledelayedexpansion
Enables the delayed environment variable expansion until the matching endlocal command is encountered, regardless of the setting prior to the setlocal command.
disabledelayedexpansion
Disables the delayed environment variable expansion until the matching endlocal command is encountered, regardless of the setting prior to the setlocal command.
/?
Displays help at the command prompt.

Remarks

  • Using setlocal

    When you use setlocal outside of a script or batch file, it has no effect.

  • Changing environmental variables

    Use setlocal to change environment variables when you run a batch file. Environment changes made after you run setlocal are local to the batch file. Cmd.exe restores previous settings when it either encounters an endlocal command or reaches the end of the batch file.

  • You can have more than one setlocal or endlocal command in a batch program (that is, nested commands).
  • Testing for command extensions in batch files

    The setlocal command sets the ERRORLEVEL variable. If you pass either {enableextension | disableextensions} or {enabledelayedexpansion | disabledelayedexpansion}, the ERRORLEVEL variable is set to zero (0). Otherwise, it is set to one (1). You can use this in batch scripts to determine whether the extensions are available, for example:

        verify other 2>nul
        setlocal enableextensions
        if errorlevel 1 echo Unable to enable extensions

    Because cmd does not set the ERRORLEVEL variable when command extensions are disabled, the verify command initializes the ERRORLEVEL variable to a nonzero value when you use it with an invalid argument. Also, if you use the setlocal command with arguments {enableextension | disableextensions} or {enabledelayedexpansion | disabledelayedexpansion} and it does not set the ERRORLEVEL variable to one (1), command extensions are not available.

    For more information about enabling and disabling command extensions, see cmd in Related Topics.

Examples

You can localize environment variables in a batch file, as follows:

  rem *******Begin Comment**************
  rem This program starts the superapp batch program on the network,
  rem directs the output to a file, and displays the file
  rem in Notepad.
  rem *******End Comment**************
      @echo off
      setlocal
      path=g:/programs/superapp;%path%
      call superapp>c:/superapp.out
      endlocal
      start notepad c:/superapp.out

6. Util

1. for %v in (*.jacl) do wsadmin -f %v

2. netstat -an | find "5000" > haha.txt

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics