- Command line parameters
- SHIFT
- Delimiters
- More options in Windows NT 4/2000/XP
- Validate command line arguments using GOTO
- original code, broken in CMD.EXE (Windows NT 4 and later):
- improved code for CMD.EXE:
- Related Stuff
- Batch-файл может принимать аргументы запуска
- Using parameters in batch files at Windows command line
- 5 Answers 5
- Checking if a parameter was passed
- Handling more than 9 arguments (or just making life easier)
- Substitution of batch parameters
- Windows Bat file optional argument parsing
- 6 Answers 6
Command line parameters
Batch files can only handle parameters %0 to %9
%0 is the program name as it was called,
%1 is the first command line parameter,
%2 is the second command line parameter,
and so on till %9 .
OK, tell me something new.
Since %0 is the program name as it was called, in DOS %0 will be empty for AUTOEXEC.BAT if started at boot time.
This means that, in AUTOEXEC.BAT, you can check if it is being started at boot time or from the command line, for example to prevent loading TSRs twice.
SHIFT
The batch file’s limitation to handle parameters up to %9 only can be overcome by using SHIFT.
Let us assume your batchfile is called with the command line parameters A B C D E F G H I J K .
Now %1 equals A, %2 equals B, etcetera, until %9 , which equals I. However, %10 does not equal J but A0; %10 is interpreted as %1 , immediately followed by a 0.
Does that mean the rest of the parameters is lost? Of course not.
After your batch file handled its first parameter(s) it could SHIFT them (just insert a line with only the command SHIFT ), resulting in %1 getting the value B, %2 getting the value C, etcetera, till %9 , which now gets the value J.
Continue this process until at least %9 is empty.
Use a loop to handle any number of command line parameters:
Note: | IF «%1″==»» will cause problems if %1 is enclosed in quotes itself. In that case, use IF [%1]==[] or, in NT 4 (SP6) and later only, IF «% 1″==»» instead. |
In Windows NT 4, 2000 and XP you can SHIFT the command line parameters starting from the nth positions using SHIFT ‘s /n switch, where n can be any (integer) number between 0 and 8: SHIFT /4 will leave %0 through %3 untouched, and shift %5 to %4 , %6 to %5 , etcetera.
To use this feature, Command Extensions should be enabled.
An easy work-around in NT 4 and later is:
No need to use SHIFT anymore.
Delimiters
Some characters in the command line are ignored by batch files, depending on the DOS version, whether they are «escaped» or not, and often depending on their location in the command line:
- commas («,») are replaced by spaces, unless they are part of a string in doublequotes
- semicolons («;») are replaced by spaces, unless they are part of a string in doublequotes
- «=» characters are sometimes replaced by spaces, not if they are part of a string in doublequotes
- the first forward slash («/») is replaced by a space only if it immediately follows the command, without a leading space
- multiple spaces are replaced by a single space, unless they are part of a string in doublequotes
- tabs are replaced by a single space
- leading spaces before the first command line argument are ignored
- trailing spaces after the last command line argument are trimmed
I know of several occasions where these seemingly useless «features» proved very handy.
Keep in mind, though, that these «features» may vary with the operating systems used.
More on command line parsing can be found on the PATH and FOR (especially FOR’s interactive examples) pages.
More options in Windows NT 4/2000/XP
Windows NT 4 introduced a set of new features for command line parameters:
%CmdCmdLine% | will return the entire command line as passed to CMD.EXE |
%* | will return the remainder of the command line starting at the first command line argument (in Windows NT 4, %* also includes all leading spaces) |
% dn | will return the drive letter of %n (n can range from 0 to 9) if %n is a valid path or file name (no UNC) |
% pn | will return the directory of %n if %n is a valid path or file name (no UNC) |
% nn | will return the file name only of %n if %n is a valid file name |
% xn | will return the file extension only of %n if %n is a valid file name |
% fn | will return the fully qualified path of %n if %n is a valid file name or directory |
Note: | %CmdCmdLine% and %* will leave all delimiters intact, except, in Windows 2000 and later, leading spaces before the first argument |
Windows 2000 and XP add even more options.
More information can be found at the page explaining NT’s CALL command.
To remove the leading space of %* included by NT 4 use the following commands:
Validate command line arguments using GOTO
Note: | Please read the Best Practices section on command line input validation |
A tip by Oliver Schneider:
original code, broken in CMD.EXE (Windows NT 4 and later):
Note: | This tip dates back to way before the Windows NT era. In CMD.EXE (Windows NT 4 and later), a batch file exits if an invalid label is specified, unless the next line tests for ERRORLEVEL 1. |
improved code for CMD.EXE:
For a limited number of allowed arguments, this is a time saving technique.
Do note, however, that labels are case sensitive, so you may not want to use this technique for «string type» arguments.
Also keep in mind that labels cannot contain delimiters (space, comma, semi-colon, etcetera), they must be unique, and that only the first 8 characters are used (so the first 8 characters must be unique!).
This technique is best used when each valid value for %1 has its own batch code to process it:
Note: | Note the extra IF ERRORLEVEL 1 test I added. It is required to make the code work in Windows 7 and 8 too. |
Related Stuff
page last uploaded: 2021-01-27, 16:12
Command extensions enable extra features in NT shells.
By default command extensions are enabled. However, to be absolutely sure that they are, either use SETLOCAL ENABLEEXTENSIONS within your NT shell scripts (batch files) or execute those scripts using CMD /X .
Likewise, you may disable command extensions using SETLOCAL DISABLEEXTENSIONS or CMD /Y .
Read my SETLOCAL page if you intend to use SETLOCAL extension switches.
Batch-файл может принимать аргументы запуска
3 . в зависимости от номера аргумента.
Чтобы получить сразу все аргументы, нужно ввести %*
Приложение Microsoft Access не может найти файл ‘C:\Windows\system32\system.mdb’ этот файл требуется для запуска
При установке Офис 97 на Windows XP не работает Access — выдается сообщение: «Приложение Microsoft.
Насколько хороша мысль принимать только rvalue аргументы?
В общем, я задумался, насколько хорошая мысль создавать публичный интерфейс только на move методах.
Создание библиотеки функций, которые могут принимать аргументы и возращать значения
Создал простую библиотеку для теста: Public Class Class1 Function teest(ByVal i As Integer).
Получить аргументы запуска приложения
Как записать значение в переменную при запуске из командной строки?
Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.
Проверить, заданы ли аргументы запуска бат-файла
Доброго дня. Подскажите, пожалуйста, как мне сделать, чтобы если пользователь не указал параметры.
Получить аргументы запуска уже работающего процесса
Вот как запустить:Dim proooc As ProcessStartInfo = New ProcessStartInfo() proooc.FileName =.
Может ли свойство принимать параметры
A) Да, но только по значению B) Нет C) Да, но только один D) Да
Какие значения может принимать переменная а
Помогите разобраться: Какие значения может принимать переменная а, если она определена следующим.
Сколько параметров может принимать функция?
Подскажите, сколько параметров может принимать функция? int foo_a();
Using parameters in batch files at Windows command line
In Windows, how do you access arguments passed when a batch file is run?
For example, let’s say I have a program named hello.bat . When I enter hello -a at a Windows command line, how do I let my program know that -a was passed in as an argument?
5 Answers 5
As others have already said, parameters passed through the command line can be accessed in batch files with the notation %1 to %9 . There are also two other tokens that you can use:
- %0 is the executable (batch file) name as specified in the command line.
- %* is all parameters specified in the command line — this is very useful if you want to forward the parameters to another program.
There are also lots of important techniques to be aware of in addition to simply how to access the parameters.
Checking if a parameter was passed
This is done with constructs like IF «%
1″==»» , which is true if and only if no arguments were passed at all. Note the tilde character which causes any surrounding quotes to be removed from the value of %1 ; without a tilde you will get unexpected results if that value includes double quotes, including the possibility of syntax errors.
Handling more than 9 arguments (or just making life easier)
If you need to access more than 9 arguments you have to use the command SHIFT . This command shifts the values of all arguments one place, so that %0 takes the value of %1 , %1 takes the value of %2 , etc. %9 takes the value of the tenth argument (if one is present), which was not available through any variable before calling SHIFT (enter command SHIFT /? for more options).
SHIFT is also useful when you want to easily process parameters without requiring that they are presented in a specific order. For example, a script may recognize the flags -a and -b in any order. A good way to parse the command line in such cases is
This scheme allows you to parse pretty complex command lines without going insane.
Substitution of batch parameters
For parameters that represent file names the shell provides lots of functionality related to working with files that is not accessible in any other way. This functionality is accessed with constructs that begin with %
For example, to get the size of the file passed in as an argument use
To get the path of the directory where the batch file was launched from (very useful!) you can use
You can view the full range of these capabilities by typing CALL /? in the command prompt.
Windows Bat file optional argument parsing
I need my bat file to accept multiple optional named arguments.
For example my command has 2 mandatory parameters, and two optional parameters (-username) that has an argument value of alice, and -otheroption:
I’d like to be able to pluck these values into variables.
Just putting out a call to anyone that has already solved this. Man these bat files are a pain.
6 Answers 6
Though I tend to agree with @AlekDavis’ comment, there are nonetheless several ways to do this in the NT shell.
The approach I would take advantage of the SHIFT command and IF conditional branching, something like this.
The selected answer works, but it could use some improvement.
- The options should probably be initialized to default values.
- It would be nice to preserve %0 as well as the required args %1 and %2.
- It becomes a pain to have an IF block for every option, especially as the number of options grows.
- It would be nice to have a simple and concise way to quickly define all options and defaults in one place.
- It would be good to support stand-alone options that serve as flags (no value following the option).
- We don’t know if an arg is enclosed in quotes. Nor do we know if an arg value was passed using escaped characters. Better to access an arg using %
1 and enclose the assignment within quotes. Then the batch can rely on the absence of enclosing quotes, but special characters are still generally safe without escaping. (This is not bullet proof, but it handles most situations)
My solution relies on the creation of an OPTIONS variable that defines all of the options and their defaults. OPTIONS is also used to test whether a supplied option is valid. A tremendous amount of code is saved by simply storing the option values in variables named the same as the option. The amount of code is constant regardless of how many options are defined; only the OPTIONS definition has to change.
EDIT — Also, the :loop code must change if the number of mandatory positional arguments changes. For example, often times all arguments are named, in which case you want to parse arguments beginning at position 1 instead of 3. So within the :loop, all 3 become 1, and 4 becomes 2.
There really isn’t that much code. Most of the code above is comments. Here is the exact same code, without the comments.
This solution provides Unix style arguments within a Windows batch. This is not the norm for Windows — batch usually has the options preceding the required arguments and the options are prefixed with / .
The techniques used in this solution are easily adapted for a Windows style of options.
- The parsing loop always looks for an option at %1 , and it continues until arg 1 does not begin with /
- Note that SET assignments must be enclosed within quotes if the name begins with / .
SET /VAR=VALUE fails
SET «/VAR=VALUE» works. I am already doing this in my solution anyway. - The standard Windows style precludes the possibility of the first required argument value starting with / . This limitation can be eliminated by employing an implicitly defined // option that serves as a signal to exit the option parsing loop. Nothing would be stored for the // «option».
Update 2015-12-28: Support for ! in option values
In the code above, each argument is expanded while delayed expansion is enabled, which means that ! are most likely stripped, or else something like !var! is expanded. In addition, ^ can also be stripped if ! is present. The following small modification to the un-commented code removes the limitation such that ! and ^ are preserved in option values.