handle command line parameters %1, %2, %3, %4 ....

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
kletho
Posts: 1
Joined: 18 Oct 2010 06:33

handle command line parameters %1, %2, %3, %4 ....

#1 Post by kletho » 18 Oct 2010 07:38

I have a question regarding command parameters (%1, %2, %3, etc…)

I have a program that accepts command parameters.

for example: programm.exe –A paramA –B paramB –C paramC –D paramD

in this case
%1 would be –A
%2 would be paramA
%3 would be –B
%4 would be paramB etc.

not all of these command parameters are necessary to start the program. one other thing is that it doesn’t matter in what order/sequence the parameters are entered. (e.g: programm.exe –D paramD –A paramA –C paramC –B paramB) with a for command how can I find out what parameters do exist


first of all I want to find out if one of those given even parameters (%2, %4, %6, %8) contain paramA

I could do this like:
if /I %2==paramA goto somewhere
if /I %4==paramA goto somewhere
if /I %6==paramA goto somewhere
if /I %8==paramA goto somewhere
::

: somewhere
:: in case someone sets the command parameter to A (-A) it replaces it with a parameter given from the system (for example the data content from %host% which was determined earlier in this script)

if %1==-A set Aparam=-A %host%
if %3==-A set Aparam=-A %host%
if %5==-A set Aparam=-A %host%
if %7==-A set Aparam=-A %host%

if %1==-C set Cparam=-C %2
if %3==-C set Cparam=-C %4
if %5==-C set Cparam=-C %6
if %7==-C set Cparam=-C %8

if %1==-B set Bparam=-B %2
if %3==-B set Bparam=-B %4
if %5==-B set Bparam=-B %6
if %7==-B set Bparam=-B %8
.
.
.
.

the problem I have here is if some command parameters are not given. eg: programm.exe –A paramA –B paramB here, only %1, %2, %3 and %4 are given. %5, %6, %7, %8 are not.

the program gets error because

if %1==-C set Cparam=-C %2
if %3==-C set Cparam=-C %4
if %5==-C set Cparam=-C %6
if %7==-C set Cparam=-C %8


if %1==-B set Bparam=-B %2
if %3==-B set Bparam=-B %4
if %5==-B set Bparam=-B %6
if %7==-B set Bparam=-B %8

%5, %6, %7, %8 (bold) is not used!!


how would you check first which command parameters are given/used? How would you do this checks with a for loop

unfortunately i'm not into batch scripting too much. hope it's not too difficult to understand what i was trying to say

thanks for your help

aGerman
Expert
Posts: 4654
Joined: 22 Jan 2010 18:01
Location: Germany

Re: handle command line parameters %1, %2, %3, %4 ....

#2 Post by aGerman » 18 Oct 2010 11:42

Try this example:

Code: Select all

@echo off &setlocal
:loop
  if "%~1"=="" goto exitLoop
  set "option=%~1"
  set "%option:~1%param=%option% %~2"
  shift
  shift
goto loop

:exitLoop

set "host=www.dostips.com"
if defined Aparam set "Aparam=-A %host%"

:: only to show what we got
echo\Aparam=%Aparam%
echo\Bparam=%Bparam%
echo\Cparam=%Cparam%
echo\Dparam=%Dparam%
pause



Regards
aGerman

Post Reply