-2

I am creating a batch program, and you need to pass arguments to it. Though with my current code you have to pass the arguments in a certain way. The way I could fix this is by getting a line of text next to the argument. This is what I want :

batch.bat -arg2 arg -arg1 arg
                 ^         ^
                 |         |
              Need This Need This
KyLeCoOl
  • 27
  • 3
  • 1
    Well `batch.bat` will see your required arguments as `%2`, _(string following `-arg2`)_, and `%4`, _(string following `-arg1`)_, is that what you wanted to know? or is there something else you wanted? Also you may be interested in the `Shift` command, please open a Command Prompt window and enter `shift /?` to read its usage information. – Compo Aug 24 '19 at 14:29
  • OK, here's my problem: My batch file has 2 different arguments, let's say -1 and -2. Those 2 arguments are required, but the user could get the order messed up, Which will make my batch file behave in a weird way. For example, batch.bat -1 arg1 -2 arg2. They are in the correct order. But batch.bat -2 arg2 -1 arg1? It will make my batch file behave in a weird way. Hope this helps. – KyLeCoOl Aug 24 '19 at 14:36
  • 2
    You should create a validation routine at the top of `batch.bat` to determine each individual argument, ordering them appropriately, or in my opinion, exiting the script with a return message to the end user telling them how they need to input their arguments. _If your end user cannot follow a basic scheme for running a script with arguments, they should not be allowed to use the command line!_ This site isn't a free script writing service, so it is your responsibility to provide the code, and ours to help you to fix it, _given your full explanation of what happened when it was run_. – Compo Aug 24 '19 at 15:28

1 Answers1

0

here is a skeleton to use. If you don't trust your users, you will have to add some precautions (like checking if arguments come in pairs or if the first argument of a pair starts with a - and the second doesn't)

@Echo Off
setlocal
:loop
if "%~2" == "" goto :continue
set "%~1=%~2"
shift
shift
goto :loop
:continue
REM check the parameters:
set - 2>nul

Try with

batch.bat -arg2 world -arg1 hello

Alternative syntax (without changing the code):

batch.bat -arg2=world -arg1=hello

(maybe better understandable by users)

Stephan
  • 50,835
  • 10
  • 55
  • 88