Windows Programming/Programming CMD
From Wikibooks, the open-content textbooks collection
Windows XP maintains 32-bit command shell cmd.exe which has roots in 16-bit command.com shell known from DOS. It was extended in subsequent versions of Windows so it's not fully compatible with command.com. It's a simple shell but it's a useful tool to use for programming and scripting a Windows workstation. This page will attempt to describe, briefly, how to program for the command prompt window. This page will discuss BATCH programming using the CMD script, and it will also talk about how to interract with the prompt using C or VB.
For a more in-depth look at the CMD commands, see: Guide to Windows commands.
Contents |
[edit] The Prompt
The command prompt can be accessed by running "cmd.exe" (for windows 2000/XP) or "command.com" (for older versions of Windows).
[edit] BATCH script
BATCH script is the unofficial term for the DOS scripting language. It is often called BATCH script because it is included in "batch files", with the ".BAT" file extension. Batch files are not compiled, but are instead interpreted on the fly by the command interpreter.
Comments in batch files are denoted either with the keyword "REM", or in more recent versions, a double colon (::).
Batch script, essentially, consists of all the command-line applications that can be run, and a few small control keywords that can be used for simple control tasks. If functionality is missing in your dos prompt, you can write a new program to handle that, and use the program in your next batch script.
Commands can be entered at the CMD prompt to be executed one at a time, or they can be assembled into a batch file. Batch files are essentially just text files, that contain listings of CMD commands to be executed. In a batch file, commands are separated by a newline, and therefore only one command can appear on each line. Batch scripts can also not easily receive user input from the keyboard, and without some sort of extension program cannot interact with the mouse at all.
[edit] Basic Commands
To print a string to the prompt, we use the ECHO command. ECHO will automatically convert any variable names, and will print the resulting string to the prompt. To print an empty line, use the command "ECHO.", with a period afterwards.
To print a prompt that says "Press any key to continue...", use the PAUSE command. PAUSE will hold the program until a key is pressed.
Typing any command, followed by the symbols "/?" will bring up the help to that command. If you are writing a command line application, it is typical to display a help message when the user types in this symbol (or a related symbol such as "-?", "-h", "/h", or "-help");
[edit] Variables
Most the variables available in the CMD window are considered "Environment Variables", although changes in the variables of a particular CMD window do not affect the values of those variables system wide. There are other special variables for use in controlling the loop structures, and for use in passing parameters to batch scripts.
To view a list of all the variables active in the current CMD window, type the command "SET". SET will display the current variables or (if you pass in the right parameters) can change the value of a particular variable or even create a new variable.
to set a variable value, we call SET as such:
SET var=value Echo be for var %var% after var
Output: be for var value after var
note that there are no spaces between the "var" and the "value".
If we want to access an environmental variable from our program, we can use the GetEnvironmentVariable WinAPI function. To set an environment variable from a C program, we can use the SetEnvironmentVariable' function. Remember that values can exist only in a certain CMD window, and that environment variables can be changed at any time by any program. It is a bad idea to store too much data in environment variables, or to rely on a particular value for program execution.
[edit] Batch Script Arguments
[edit] IF THEN ELSE
IF Boolean Expression (
True Statements
) ELSE (
False Statements
)
Example
REM %1 Database Name
set myDB=zzz--%1--zzz
REM No database name given
IF %myDB% == zzz----zzz (
echo ------------
echo default_db Backup!
echo ------------
mysqldump -u root -p default_db > default_db.mysql.dump
) ELSE (
echo ------------
echo %1 Backup!
echo ------------
mysqldump -u root -p %1 > %1.mysql.dump
)
[edit] FOR looping
Runs a specified command for each file in a set of files.
FOR %variable IN (set) DO command [command-parameters]
%variable Specifies a single letter replaceable parameter.
(set) Specifies a set of one or more files. Wildcards may be used.
command Specifies the command to carry out for each file.
command-parameters
Specifies parameters or switches for the specified command.
To use the FOR command in a batch program, specify %%variable instead of %variable. Variable names are case sensitive, so %i is different from %I.
Batch File Example:
for %%F IN (*.txt) DO @echo %%F
This command will list all the files ending in .txt in the current directory.
If Command Extensions are enabled, the following additional forms of the FOR command are supported:
FOR /D %variable IN (set) DO command [command-parameters]
If set contains wildcards, then specifies to match against directory names instead of file names.
FOR /R [[drive:]path] %variable IN (set) DO command [command-parameters]
Walks the directory tree rooted at [drive:]path, executing the FOR statement in each directory of the tree. If no directory specification is specified after /R then the current directory is assumed. If set is just a single period (.) character then it will just enumerate the directory tree.
FOR /L %variable IN (start,step,end) DO command [command-parameters]
The set is a sequence of numbers from start to end, by step amount. So (1,1,5) would generate the sequence 1 2 3 4 5 and (5,-1,1) would generate the sequence (5 4 3 2 1)
FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ("string") DO command [command-parameters]
FOR /F ["options"] %variable IN ('command') DO command [command-parameters]
or, if usebackq option present:
FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ('string') DO command [command-parameters]
FOR /F ["options"] %variable IN (`command`) DO command [command-parameters]
filenameset is one or more file names. Each file is opened, read and processed before going on to the next file in filenameset. Processing consists of reading in the file, breaking it up into individual lines of text and then parsing each line into zero or more tokens. The body of the for loop is then called with the variable value(s) set to the found token string(s). By default, /F passes the first blank separated token from each line of each file. Blank lines are skipped. You can override the default parsing behavior by specifying the optional "options" parameter. This is a quoted string which contains one or more keywords to specify different parsing options. The keywords are:
eol=c - specifies an end of line comment character
(just one)
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.
This will cause additional variable names to
be 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, then an additional variable is
allocated and receives the remaining text on
the line after the last token parsed.
usebackq - specifies that the new semantics are in force,
where a back quoted string is executed as a
command and a single quoted string is a
literal string command and allows the use of
double quotes to quote file names in
filenameset.
Some examples might help:
FOR /F "eol=; tokens=2,3* delims=, " %i in (myfile.txt) do @echo %i %j %k
would parse each line in myfile.txt, ignoring lines that begin with a semicolon, passing the 2nd and 3rd token from each line to the for body, with tokens delimited by commas and/or spaces. Notice the for body statements reference %i to get the 2nd token, %j to get the 3rd token, and %k to get all remaining tokens after the 3rd. For file names that contain spaces, you need to quote the filenames with double quotes. In order to use double quotes in this manner, you also need to use the usebackq option, otherwise the double quotes will be interpreted as defining a literal string to parse.
%i is explicitly declared in the for statement and the %j and %k are implicitly declared via the tokens= option. You can specify up to 26 tokens via the tokens= line, provided it does not cause an attempt to declare a variable higher than the letter 'z' or 'Z'. Remember, FOR variables are single-letter, case sensitive, global, and you can't have more than 52 total active at any one time.
You can also use the FOR /F parsing logic on an immediate string, by making the filenameset between the parenthesis a quoted string, using single quote characters. It will be treated as a single line of input from a file and parsed.
Finally, you can use the FOR /F command to parse the output of a command. You do this by making the filenameset between the parenthesis a back quoted string. It will be 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 was a file. So the following example:
FOR /F "usebackq delims==" %i IN (`set`) DO @echo %i
would enumerate the environment variable names in the current environment.
In addition, substitution of FOR variable references has been enhanced. You can now use the following optional syntax:
%~I - expands %I removing any surrounding quotes (")
%~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 - expanded path contains short names only
%~aI - expands %I to file attributes of file
%~tI - expands %I to date/time of file
%~zI - expands %I to 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, then this modifier expands to the
empty string
The modifiers can be combined to get compound results:
%~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 a DIR like output line
In the above examples %I and PATH can be replaced by other valid values. The %~ syntax is terminated by a valid FOR variable name. Picking upper case variable names like %I makes it more readable and avoids confusion with the modifiers, which are not case sensitive.
[edit] Pipes
this is mainly used to redirect the output of one program to another program >> a | b
means execute "a" and what all output "a" gives to the console - give that as "b" s input
>> dir | find ".htm" will give a list of file which contain ".htm" in their names
[edit] Command-Line Interfacing
let's say we want to call a program "MyProgram" from the command prompt. we type the following into our prompt (the .exe file extension is unnecessary):
C:\>myprogram.exe
And this will run the myprogram executable. Now, let's say we want to pass a few arguments to this program:
C:\>myprogram arg1 arg2 arg3
Now, if we go into the standard main function, we will have our argc and argv values:
int main(int argc, char *argv[])
Where:
argc = 4 argv[0] = "myprogram" (the name of the program - deduct 1 from argc to get the number of arguments) argv[1] = "arg1" argv[2] = "arg2" argv[3] = "arg3"
This shouldn't come as a big surprise to people who have any familiarity with standard C programming. However, if we translate this to our WinMain function, we get a different value:
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR CmdLine, int iCmdShow)
we will only have one value to accept the command line:
CmdLine = "myprogram arg1 arg2 arg3".
We can also use the function GetCommandLine to retrive this string from any point in the application. If we want to parse this into a standard argv/argc pair, we can use the function CommandLineToArgvW to perform the conversion. It is important to note that CommandLineToArgvW only works on unicode strings.
When we return a value from our C program, that value gets passed to the CMD shell, and stored in a variable called "ERRORLEVEL". ERRORLEVEL is the only global variable that is not a string, and it can contain a number from 0 to 255. By convention, a value of zero means "success", while a value other then zero signifies an error.
Let's say we wanted to write a C program that returns the number of arguments passed to it. This might sound like a simple task in C, but it is difficult to accomplish in batch script:
int main(int argc, char *argv[])
{
return (argc - 1);
}
And we will name this program "CountArgs.exe". Now, we can put this into a batch script, to pass it a number of arguments, and to print out the number passed:
countargs.exe %* ECHO %ERRORLEVEL%
We can, in turn, call this script "count.bat", and run that from a command prompt:
C:\>count.bat arg1 arg2 arg3
and running this will return the answer: 3.
NOTE: Actually, this can be accomplished with a batch file without resorting to a C program, by simply using CMD delayed variable expansion via the "/V:ON" parameter:
/V:ON Enable delayed environment variable expansion using ! as the delimiter. For example, /V:ON would allow !var! to expand the variable var at execution time. The var syntax expands variables at input time, which is quite a different thing when inside of a FOR loop.
Then use a simple batch file like the following to count parameters:
set COUNT=0 for %%x in (%*) do ( set /A COUNT=!COUNT!+1 ) echo %COUNT%
Or an easier way, without having to enable & use 'delayed environment expansion', would be to do the following - DVM ;) :
set argC=0 for %%x in (%*) do Set /A argC+=1 echo argC - %argC% cls
This returns the same answer as the C program example.