1

I would like to know if it is possible to use my own named parameters when running a batch file.

For example I have a deploy.bat and I would like to call it from my command line like, does not matter if I will user double or single dashes:

C:\> deploy.bat --user=admin --password=1234

Is that possible?

Panagiotis
  • 201
  • 3
  • 16
  • With regard to the linked duplicate question above, pay particular attention to [this answer](https://stackoverflow.com/a/8162578/1012053), as it gives a rather elegant solution. – dbenham Dec 16 '17 at 21:29

2 Answers2

4

Here are two ways (other approaches are possible too) , assuming arguments will be the same as in the question:

@echo off
:: mind that '=' will be taken as blank space when parsing arguments.
:: and `--user=admin` are two arguments.

:: 1) with for /l
setlocal enableDelayedExpansion
rem max count of the expected arguments
set max_count=10


for /l %%# in (1,2,%max_count%) do (
    set /a next=%%#+1
    set curr=%%#
    call set "%%~!curr!=%%~!next!" 2>nul
)
echo %--user% -- %--password%

:::::::::::::::::
:: 2) processing the arguments line
setlocal enableDelayedExpansion
set "prev="
set "current="



for %%a in (%*) do (
    set "current=%%~a"
    if  defined prev (
        set "!prev!=%%~a"
        set "prev="
    ) else (
        set prev=%%a
    )
)

echo %--user% -- %--password%

Explanation: With the both ways I'm proccessing the arguments through one. Also the = sign is a standard delimiter for cmd.exe and it will be threated as blank space.

1)In the first approach I'm processing all arguments with FOR /L loop (it acts like the for loop in the c-like syntax languages) with step 2 and on each step I also have the next number.Under delayed expansion I can parametrize the number of the argument and get it like call echo %%~!number! which allows me to use a argument-value couple to set the variables. One impediment is you can't process more than 9 arguments in this way (or you'll have to add shift somewhere in the loop)

2) In the second one I'm processing the whole argument line.I have one additional variable prev that is deleted on each even step and on each odd step it takes the value of the current argument.So on each even step I have argument-value couple.

npocmaka
  • 55,367
  • 18
  • 148
  • 187
1

Batch files support positional parameters only, and are addressed as %1, %2, etc. If you want to go through the exercise of parsing strings manually - possible, but not a trivial exercise - you can simulate this, but it's probably not worth the effort.

PowerShell is a much richer scripting environment, and does support named parameters.

Jeff Zeitlin
  • 9,773
  • 2
  • 21
  • 33