Logo
programming4us
programming4us
programming4us
programming4us
Home
programming4us
XP
programming4us
Windows Vista
programming4us
Windows 7
programming4us
Windows Azure
programming4us
Windows Server
programming4us
Windows Phone
 
Windows Server

Windows Server 2008 Server Core : Creating Batch Files (part 2) - Using the For Command

- Free product key for windows 10
- Free Product Key for Microsoft office 365
- Malwarebytes Premium 3.7.1 Serial Keys (LifeTime) 2019
4/25/2012 4:11:48 PM

3. Using the Echo Command

The command line uses the term echo to describe the process where the system echoes (repeats) every command in a batch file to the command line. Echo provides a means of seeing which command the system is processing. However, echo can become confusing for users who aren't aware of or don't care about the commands that are executing. In addition, echo can disrupt visual effects, such as menu systems, that you create. The Echo command has two forms. The first form

ECHO [{ON | OFF}]

displays the echo status when you don't include any arguments. The ON argument turns on echo so you can see the commands, and the OFF argument turns off echo so you can create visual effects. You can precede the Echo command with the @ sign so it doesn't appear as one of the commands. @Echo OFF would turn echo off without displaying the echo command at the command prompt.

The second form of echo

ECHO [message]

lets you display a message. Simply type the text you want to see after the Echo command. In this case, the system won't display the Echo command, just the message you want to display. Don't use the @ sign with this form of the Echo command or the user won't see the message.

4. Using the Exit Command

Most people associate the Exit command with closing the current command window. Using Exit alone will close the command window. However, you can also use this command within a batch file to exit the batch file. To perform this task, you must use one or both of the following optional Exit arguments.


/B

Specifies that you want to exit a batch file, rather than the current command line session. If you don't specify this command line switch, the command window closes, even when you issue the Exit command from a batch file.


ExitCode

Defines an exit code for the batch file. The default exit code is 0, which normally signifies success. You can use exit codes to alert the caller to errors or special conditions. The exit codes aren't defined by the system, so you can define any set of exit codes that you deem necessary for your application.

5. Using the ForFiles Utility

The ForFiles utility provides a means of looping through a list of files and performing actions on those files one at a time. For example, you might want to process all files that someone has changed since a certain date. This command uses the following syntax:

FORFILES [/P pathname] [/M searchmask] [/S] [/C command]
[/D [+ | -] {MM/dd/yyyy | dd}]

The following list describes each of the command line arguments.

/P pathname

Specifies the starting point for a search. The path is the starting folder in the search. The default setting uses the current directory as the starting point.

/M searchmask

Defines a search mask for the files. You can use the asterisk (*) and question mark (?) as wildcard characters, just as you would when using the Directory command. The default setting searches for all files in the target directory.

/S

Searches all of the subdirectories of the specified directory.

/C command

Specifies the command you want to execute for each file. Always wrap the command in double quotes to ensure it isn't interpreted as part of the ForFile command. The default command is "cmd /c echo @file". Always precede internal command processor command with cmd /c. The following list describes the variables that you can use as part of the command.

@file

Returns the name of the file, including the file extension.

@fname

Returns the name of the file without the extension.

@ext

Returns only the file extension.

@path

Returns the full path of the file. This information includes the drive as well as the actual path.

@relpath

Returns the relative path of the file. The relative path begins at the starting folder.

@isdir

Specifies whether the file type is a directory. True indicates a directory entry.

@fsize

Indicates the size of the file in bytes.

@fdate

Indicates the date that someone last modified the file.

@ftime

Indicates the time that someone last modified the file.

You can include special characters in a command by using the 0xHH format where HH is a hexadecimal number. For example, you can specify a tab by typing 0x09.


/D date

Selects files that have a last modified date within the specified range. You specify a specific date using the month/day/year (mm/dd/yyyy) format. Add a plus sign if you want files after the specified date or a minus sign if you want files before the specified date. For example, /D-01/01/2008 would select all files modified before January 1, 2008. You can also specify a relative date by providing a positive or negative number. For example, /D-7 would select all files modified within the last seven days. The /D command line switch accepts any number between 0 and −32,768.

6. Using the For Command

The For command fulfills a special niche in batch file programming. Unfortunately, using wildcard characters won't always work. Sometimes you need to know the name of the file. A command line utility might not support wildcard characters or the file argument doesn't easily fit within the wildcard method of description. That's where the For statement comes into play for batch files. This command takes the form:

FOR %%variable IN (set) DO command [command-parameters]

You can also use this command at the command prompt to process files manually. Instead of using a single percent (%) symbol, you use two in front of the variable. Here's a sample of how you can use this command in a batch file.

Echo Off
For %%F In (*.BAT *.TXT) Do Dir %%F /B
Echo On

In this case, the For command processes all of the files that have a BAT or TXT extension in the current directory. The command processes the files in the order in which they appear in the directory and you have no guarantee what the order is. The %%F variable contains the name of an individual file. The Dir command is called once for each file with the %%F variable as an input. In this case, the command outputs the filenames using the bare format, so you could use this batch file to create a text file containing a list of files that match the criteria. Additional processing could archive the files or do anything else that you might like. The For command provides the following arguments.


{%Variable | %%Variable}

Specifies a replaceable parameter; the argument that will receive the individual members of a set. The replaceable parameter takes two forms. Use the %Variable form when you want to use the replaceable parameter as input to another command or utility. Use the %%Variable form when you want to use the replaceable parameter for activities within the batch file. The variable names are case sensitive, so %f isn't the same as %F. In addition, you must use an alphabetical variable name, such as %A, %B, or %C.

(Set)

Defines the set to process. The set can include one or more files, directories, range of values, or text strings that you want to process with the specified command. For example, you can use environment variables as the set. The command For %%P In (%PATH%) Do ECHO %%P would display the members of the PATH environment variable as individual strings.

Command

Specifies the command you want to perform for each entry in the set.

CommandLineOptions

Defines the command line options for the command that you want to perform for each entry in the set.

6.1. Performing Complex File Iteration

You can use the For command to process command output, strings, and the content of files. In this case, the For command begins by breaking the input into individual lines of content and discarding any blank lines. It then breaks whatever input you provide into specific tokens based on the rules you specify. A token can be a control character, a special word, or anything else you can define as part of the simple syntax for this command. The For command passes the token to a command you specify as input. Here's the command line syntax for this form of the For command.

for /F ["ParsingKeywords"] {%% | %}Variabe lin (FileNameSet) do Command
   [CommandLineOptions]

for /F ["ParsingKeywords"] {%% | %}Variable in ("LiteralString") do
    Command [CommandLineOptions]
for /F ["ParsingKeywords"] {%% | %}Variable in ('Command') do Command
   [CommandLineOptions]

Notice that you need to use a different command line syntax for each kind of input. A filename appears without quotes, while a string appears in double quotes and a command appears in single quotes. The small differences in command format determines how the For command views the input.

The ParsingKeywords input is a quoted string that specifies the rules for parsing the input into tokens. These keywords always appear in double quotes, as shown. The following list describes the keywords you can use.

eol=c

Specifies an end of line character. The For command only allows you to specify one character.

skip=N

Specifies the number of lines to skip at the beginning of the file.

delims=xxx

Specifies a delimiter set. The delimiter set defines which characters the For command views as elements between tokens. The default setting relies on the space and tab. Consequently, the For command produces a new token every time it sees a space or tab within the input.

tokens=X,Y,M-N

Defines which tokens to retrieve from each line of text to pass to the For command body for each iteration. The For command allocates one variable for each of the tokens. The M-N format defines a range of tokens to use as input. Whenever the last character in a processed string is an asterisk (*), the For command creates an additional variable to receive the additional text on the line after the For command parses the last token.

usebackq

Specifies that you can use quotation marks to quote filenames in FileNameSet, a back quoted string is executed as a command, and a single quoted string is a literal string command.

You need to use a slightly different command line syntax with the For command when you rely on the usebackq keyword. Here are the three command lines using this syntax.

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]

6.2. Using Variable Substitution

Variable substitution is the act of exchanging a variable name for the content of that variable. However, unlike expansion, you don't necessarily use all of the variable content. For example, instead of using the entire path for a file, you might just use the drive letter, the path, or the filename. The following list describes the basic forms of variable substitution available with the For command. (The list assumes that you're using a variable named I, which translates into %I at the command line.)

%~I

Removes any surrounding quotation marks from the variable content.

%~fI

Expands %I to a fully qualified pathname.

%~dI

Expands %I to a drive letter only.

%~pI

Expands %I to a path only.

%~nI

Expands %I to a filename only.

%~xI

Expands %I to a file extension only.

%~sI

Creates a path variable, and then changes any long directory names into their short name equivalents.

%~aI

Obtains the file attributes of the input file.

%~tI

Obtains the date and time of the input file.

%~zI

Obtains the size of the input file.

%~$PATH:I

Searches the directories listed in the PATH environment variable for the file specified by I. The system then expands the first match that it finds to a fully qualified filename, which includes the drive, path, and filename. This variable substitution returns an empty string when the PATH environment variable is undefined or if the system can't find a match for the filename.

You can use these variable substitutions in combination to produce specific results. For example, you might want to create a directory-like listing of files. The following list provides some ideas on how to use the variable substitution arguments in combination.

%~dpI

Outputs just the drive letter and path of a file, without including the filename.

%~nxI

Outputs the filename and extension, but leaves out the drive letter and path.

%~fsI

Outputs the file information using the short name (8.3 format) form only.

%~dp$PATH:I

Locates the file using the PATH environment variable. The system outputs just the drive letter and path of the first match found.

%~ftzaI

Creates the same output as the Dir command. However, the output is different from the Dir command because the file listing could span multiple directories. The focus of the listing is different.

Other -----------------
- Microsoft Content Management Server : Using SharePoint to Display MCMS Content (part 3) - The MCMS Pages Waiting for Approval Web Part
- Microsoft Content Management Server : Using SharePoint to Display MCMS Content (part 2) - A Custom View for the MCMS Page Listing Web Part
- Microsoft Content Management Server : Using SharePoint to Display MCMS Content (part 1) - Installing the MCMS Connector Web Parts & MCMS Page Listing Web Part
- Active Directory Domain Services 2008 : Create an Organizational Unit
- Active Directory Domain Services 2008 : Modify a Computer Object’s Managed By Properties, Modify a Computer Object’s Protection from Deletion & Modify a Computer Object’s Custom Attributes
- Exchange Server 2010 : Monitoring Events, Services, Servers, and Resource Usage (part 2) - Monitoring Exchange Messaging Components & Using Performance Alerting
- Exchange Server 2010 : Monitoring Events, Services, Servers, and Resource Usage (part 1) - Viewing Events & Managing Essential Services
- Windows Server Enterprise Administration : Managing Software Update Compliance (part 2) - Planning and Deploying Security Baselines
- Windows Server Enterprise Administration : Managing Software Update Compliance (part 1) - Microsoft Baseline Security Analyzer
- Windows Server 2003 : Command-Line Utilities - SCWCMD & MBSACLI
 
 
Top 10
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
 
programming4us
Windows Vista
programming4us
Windows 7
programming4us
Windows Azure
programming4us
Windows Server