Wednesday, 18 June 2014

For command

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

Syntax

for {%variable|%%variablein (set) do command [ CommandLineOptions]


 

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.

tokens=x,y,m-n

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 themth 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).

Variable with modifier

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.

Variable with combined modifiers

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 %~ syntax.

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, "File Name"). 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.

Exit command

Exits the current batch script or the Cmd.exe program (that is, the command interpreter) and returns to the program that started Cmd.exe or to the Program Manager.

Syntax

exit [/b] [ExitCode]


 

Parameters

/b   Exits the current batch script.

ExitCode   Specifies a numeric number.

/?   Displays help at the command prompt.


 

Remarks

  • If you use /b outside of a batch script, it will exit Cmd.exe.
  • If you use /b, Cmd.exe sets the ERRORLEVEL to the specified ExitCode. If you exit Cmd.exe, Cmd.exe sets the process exit code with the specified ExitCode.


 

Goto command

Within a batch program, directs Windows XP to a line identified by a label. When the label is found, it processes the commands that begin on the next line.

Syntax

goto label


 

Parameters

label   Specifies the line in a batch program that you want to go to.

/?   Displays help at the command prompt.


 

Remarks

  • Working with command extensions

    If command extensions are enabled (that is, the default) and you use the goto command with a target label of :EOF, you transfer control to the end of the current batch script file and exit the batch script file without defining a label. When you use goto with the :EOF label, you must insert a colon before the label. For example:

    goto :EOF

    For a description of extensions to the call command that make this feature useful, see cmd in Related Topics.

  • Using valid label values

    You can use spaces in the label parameter, but you cannot include other separators (for example, semicolons or equal signs). The goto command uses only the first eight characters of a label. For example, the following labels are equivalent and resolve to :hithere0:

    :hithere0

    :hithere01

    :hithere02

  • Matching label with the label in the batch program

    The label value you specify must match a label in the batch program. The label within the batch program must begin with a colon (:). Windows XP recognizes a batch program line beginning with a colon (:) as a label and does not process it as a command. If a line begins with a colon, any commands on that line are ignored. If your batch program does not contain the label that you specify, the batch program stops and displays the following message:

    Label not found

  • Using goto for conditional operations

    You can use goto with other commands to perform conditional operations. For more information about using goto for conditional operations, see if in Related Topics.


 

Examples

The following batch program formats a disk in drive A as a system disk. If the operation is successful, the goto command directs Windows XP to the :end label:

echo off

format a: /s

if not errorlevel 1 goto end

echo An error occurred during formatting.

:end

echo End of batch program.

Pause command

Suspends processing of a batch program and displays a message prompting the user to press any key to continue.

Syntax

pause


 

Parameters

/?   Displays help at the command prompt.


 

Remarks

  • When you run prompt command, the following message appears:

    Press any key to continue . . .

  • If you press CTRL+C to stop a batch program, the following message appears:

    Terminate batch job (Y/N)?

    If you press Y (for yes) in response to this message, the batch program ends and control returns to the operating system. Therefore, you can insert the pause command before a section of the batch file you may not want to process. While pause suspends processing of the batch program, you can press CTRL+C and then Y to stop the batch program.


 

Examples

To create a batch program that prompts the user to change disks in one of the drives, type:

@echo off

:begin

copy a:*.*

echo Please put a new disk into drive A

pause

goto begin

In this example, all the files on the disk in drive A are copied to the current directory. After the displayed comment prompts you to place another disk in drive A, the pause command suspends processing so that you can change disks and then press any key to resume processing. This particular batch program runs in an endless loop. The goto BEGIN command sends the command interpreter to the begin label of the batch file. To stop this batch program, press CTRL+C and then Y.

Findstr command

Searches for patterns of text in files using regular expressions.

Parameters

/b   Matches the pattern if at the beginning of a line.

/e   Matches the pattern if at the end of a line.

/l   Uses search strings literally.

/r   Uses search strings as regular expressions. Findstr interprets all metacharacters as regular expressions unless you use /l.

/s   Searches for matching files in the current directory and all subdirectories.

/i   Specifies that the search is not to be case-sensitive.

/x   Prints lines that match exactly.

/v   Prints only lines that do not contain a match.

/n   Prints the line number before each line that matches.

/m   Prints only the file name if a file contains a match.

/o   Prints seek offset before each matching line.

/p   Skips files with non-printable characters.

/offline   Processes files with offline attribute set.

/f: file   Reads file list from the specified file.

/c: string   Uses specified text as a literal search string.

/g: file   Gets search strings from the specified file.

/d: dirlist   Searches a comma-delimited list of directories.

/a: ColorAttribute   Specifies color attributes with two hexadecimal digits.

strings   Specified text to be searched for in FileName.

[ Drive : ][ Path ] FileName [...] : Specifies a file or files to search.

/?   Displays help at the command prompt.


 

Remarks

  • Using regular expressions with findstr 

    Findstr is capable of finding the exact text you are looking for in any ASCII file or files. However, sometimes you have only part of the information that you want to match, or you want to find a wider range of information. In such cases, findstr has the powerful capability to search for patterns of text using regular expressions.

    Regular expressions are a notation for specifying patterns of text, as opposed to exact strings of characters. The notation uses literal characters and metacharacters. Every character that does not have special meaning in the regular expression syntax is a literal character and matches an occurrence of that character. For example, letters and numbers are literal characters. A metacharacter is a symbol with special meaning (an operator or delimiter) in the regular-expression syntax.

    The following table lists the metacharacters that findstr accepts.

Character

Value

.

Wildcard: any character

*

Repeat: zero or more occurrences of previous character or class

^

Line position: beginning of line

$

Line position: end of line

[class]

Character class: any one character in set

[^class]

Inverse class: any one character not in set

[x-y]

Range: any characters within the specified range

\x

Escape: literal use of metacharacter x

\<xyz

Word position: beginning of word

xyz\>

Word position: end of word

The special characters in regular expression syntax are most powerful when you use them together. For example, the following combination of the wildcard character (.) and repeat (*) character match any string of characters:

.*

Use the following expression as part of a larger expression that matches any string beginning with "b" and ending with "ing":

b.*ing


 

Examples

Use spaces to separate multiple search strings unless the argument is prefixed with /c. To search for "hello" or "there" in file x.y, type:

findstr "hello there" x.y

To search for "hello there" in file x.y, type:

findstr /c:"hello there" x.y

To find all occurrences of the word "Windows" (with an initial capital W) in the file Proposal.txt, type the following:

findstr Windows proposal.txt

To search every file in the current directory and all subdirectories that contained the word Windows, regardless of the letter case, type the following:

findstr /s /i Windows *.*

To find all occurrences of lines that contain the word "FOR", preceded by any number of spaces, (as in a computer program loop), and to include the line number where each occurrence is found, type the following:

findstr /b /n /c:" *FOR" *.bas

If you want to search for several different items in the same set of files, create a text file that contains each search criterion on a new line. You can also list the exact files you want to search in a text file. To use the search criteria in the file Finddata.txt, search the files listed in Filelist.txt, and then store the results in the file Results.out, type the following:

findstr /g:finddata.txt /f:filelist.txt > results.out

Assume you wanted to find every file in the current directory and all subdirectories that contained the word computer, regardless of the letter case. To list every file containing the word computer, type the following:

findstr /s /i /m "\<computer\>" *.*

Now assume you want to find not only the word "computer," but also any other words that begin with the letters comp, such as "compliment" and "compete. " type the following:

findstr /s /i /m "\<comp.*" *.*

Net services commands

Pushd command

Stores the name of the current directory for use by the popd command before changing the current directory to the specified directory.

Syntax

pushd [Path]


 

Parameters

Path   Specifies the directory to which the current directory should be changed. This command supports relative paths.

/?   Displays help at the command prompt.


 

Remarks

  • Every time you use the pushd command, a single directory is stored for your use. However, you can store multiple directories by using the pushd command multiple times.

    The directories are stored sequentially in a virtual stack. If you use the pushd command once, the directory in which you use the command is placed at the bottom of the stack. If you use the command again, the second directory is placed on top of the first one. The process repeats every time you use the pushd command.

    You can use the popd command to change the current directory to the directory most recently stored by the pushd command. If you use the popd command, the directory on the top of the stack is removed from the stack as the current directory is changed to that directory. If you use the popd command again, the next directory on the stack is removed.
  • If command extensions are enabled, the pushd command accepts either a network path or a local drive letter and path.
  • If you specify a network path, the pushd command temporarily assigns the first unused drive letter (starting with Z:) to the specified network resource. The command then changes the current drive and directory to the specified directory on the newly assigned drive. If you use the popd command with command extensions enabled, the popd command removes the drive-letter assignation created by pushd.


 

Examples

You can use the pushd command and the popd command in a batch program to change the current directory from the one in which the batch program was run and then change it back. The following sample batch program shows how to do this:

@echo off

rem This batch file deletes all .txt files in a specified directory

pushd %1

del *.txt

popd

cls

echo All text files deleted in the %1 directory

Popd command

Changes the current directory to the directory stored by the pushd command.

Syntax

popd


 

Parameters

/?   Displays help at the command prompt.


 

Remarks

  • Every time you use the pushd command, a single directory is stored for your use. However, you can store multiple directories by using the pushd command multiple times.

    The directories are stored sequentially in a virtual stack. If you use the pushd command once, the directory in which you use the command is placed at the bottom of the stack. If you use the command again, the second directory is placed on top of the first one. The process repeats every time you use the pushd command.

    You can use the popd command to change the current directory to the directory most recently stored by the pushd command. If you use the popd command, the directory on the top of the stack is removed from the stack as the current directory is changed to that directory. If you use the popd command again, the next directory on the stack is removed.
  • When command extensions are enabled, the popd command removes any drive-letter assignations created by pushd.


 

Examples

You can use pushd and popd in a batch program to change the current directory from the one in which the batch program was run and then change it back. The following sample batch program shows how to do this:

@echo off

rem This batch file deletes all .txt files in a specified directory

pushd %1

del *.txt

popd

cls

echo All text files deleted in the %1 directory

Mkdir command

Creates a directory or subdirectory.

Syntax

mkdir [Drive:]Path

md [Drive:]Path


 

Parameters

Drive :   Specifies the drive on which you want to create the new directory.

Path   Required. Specifies the name and location of the new directory. The maximum length of any single path is determined by the file system.

/?   Displays help at the command prompt.


 

Remarks

  • When you enable command extensions (that is, the default), you can use a single mkdir command to create intermediate directories in a specified path. For more information about enabling and disabling command extensions, see cmd in Related Topics.


 

Examples

To create a directory named Taxes with a subdirectory named Property, which contains a subdirectory named Current, type:

mkdir \Taxes\Property\Current

This is the same as typing the following sequence of commands with command extensions disabled:

mkdir \Taxes 
chdir \Taxes 
mkdir Property 
chdir Property 
mkdir Current 

Cd command

Change directory command.

Displays the name of the current directory or changes the current folder. Used with only a drive letter (for example, chdir C:), chdir displays the names of the current drive and folder. Used without parameters, chdirdisplays the current drive and directory.

Syntax

chdir [[/d] [Drive:][Path] [..]] [[/d] [Drive:][Path] [..]]

cd [[/d] [Drive:][Path] [..]] [[/d] [Drive:][Path] [..]]


 

Parameters

/d   Changes the current drive or the current directory for a drive.

[ drive : ][ Path ] : Specifies the drive (that is, if it is different from the current drive) and directory to which you want to change.

[ .. ] : Specifies that you want to change to the parent folder.

/?   Displays help at the command prompt.


 

Remarks

  • Working with command extensions

    With command extensions enabled (that is, the default), the current directory path matches the folder names exactly as they appear on your hard drive, using the same uppercase or lowercase folder-name format. For example, if the folder on your hard drive is called C:\Temp, CD C:\TEMP sets the current directory to C:\Temp to match the folder-name format of the folder on your hard drive.

    To disable command extensions for a particular process, type:

    cmd e:off

    When you disable command extensions, chdir does not treat white spaces as delimiters. As a result, you can change to a subdirectory name that contains a white space without having to surround [Path] in quotation marks. For example, the following path changes to the \Start menu subdirectory:

    cd \winnt\profiles\username\programs\start menu

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

  • Changing to the root directory

    The root directory is the top of the directory hierarchy for a drive. To return to the root directory, type:

    cd\

  • Changing the default directory on one drive from another drive

    To change the default directory on a drive different from the one you are on, type one of the following:

    chdir [Drive:\[directory]]

    cd [Drive:\[directory]]

    To verify the change to the directory, type one of the following:

    chdir [Drive:]

    cd [Drive:]

  • The chdir command, with different parameters, is available from the Recovery Console.


 

Examples

When you use it with a drive name, chdir displays the current directory for that drive. For example, if you type cd c: at the C:\Temp directory prompt, the following appears:

C:\Temp

To change your current directory to a directory named Reports, type one of the following commands:

chdir \reports

cd \reports

To change your current directory to a subdirectory \Specials\Sponsors, type:

cd \specials\sponsors

Or, if your current directory is \Specials, type the following command to change to the \Specials\Sponsors subdirectory:

cd sponsors

To change from a subdirectory to its parent directory, type:

cd ..

To display the name of the current directory, you can use chdir or cd without a parameter. For example, if your current directory is \Public\Jones on drive B, typing chdir the following appears:

B:\Public\Jones

If you are working on drive D and you want to copy all files in the \Public\Jones and \Public\Lewis directories on drive C to the root directory on drive D, type:

chdir c:\public\jones

copy c:*.* d:\

chdir c:\public\lewis

copy c:*.* d:\

If you want to copy all files in the \Public\Jones and \Public\Lewis directories to your current location on drive D, type:

chdir c:\public\jones

copy c:*.* d:

chdir c:\public\lewis

copy c:*.* d:

If command

Performs conditional processing in batch programs.

Syntax

if [noterrorlevel number command [else expression]

if [notstring1==string2 command [else expression]

if [notexist FileName command [else expression]

If command extensions are enabled, use the following syntax:

if [/istring1 CompareOp string2 command [else expression]

if cmdextversion number command [else expression]

if defined variable command [else expression]


 

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 elseclause, 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