Home > front end >  How to pass parameter with value in batch?
How to pass parameter with value in batch?

Time:11-03

Is it possible to pass multiple parameters with value in a batch file?

Here's what the command line should looks like:

> example.bat /L:10 /D:30 /R:15

And want to be able to pass in the parameters in any order and put their value in specific variables like this:

set "loop=10"
set "delay=30"
set "retry=15"

I'm using this for now:

set "loop=%1"
set "delay=%2"
set "retry=%3"

But the problem is if any argument is not passed then it doesnt work and I want to use default value if any argument is not given.

CodePudding user response:

I see absolutely no need to define variables loop, delay, and retry, when you could so very easily use variable names matching your input, (L, D, and R), or probably better, prefixed; something like varL, varD, and varR.

Example:

@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion

Rem Ensure that there are no existing variables named with var prefixes
For /F "Delims==" %%G In ('"(Set var) 2>NUL"') Do Set "%%G="

Rem Define your defaults below
Set /A "varD=3,varL=10,varR=5"

Rem Define new variable values from input arguments 
For %%G In ("%*") Do For %%H In (%%~G) Do (Set "_=%%~H"
    SetLocal EnableDelayedExpansion
    For /F "Tokens=1,* Delims=:" %%I In ("!_:~1,1!=!_:~3!") Do (EndLocal
        Set "var%%I"))

Rem The below lines are included just to show you the defined variables
Set var
Pause
  • Related