0

I got a requirement to create batch file with multiple optional parameters.

Example

MyTestSqlBatch.bat ServerName DatabaseName [UserId] [Password] [Command] [parameter]

here ServerName and DatabaseName are mandatory. And UserId, Password are optional for Windows authentication users. Command is also optional parameter (some times I need to call batch file with Command parameter for Windows authentication). if I want to run my batch file for SQL authentication then I want to pass UserId password also.

Can any one give suggest on this, how to create named parameters (or) any best way to handle this?

Thanks,

Jagadeesh
  • 1,630
  • 8
  • 24
  • 35

2 Answers2

2

Simpler:

@echo off
setlocal

set "params=%*"
set "%params: =" & set "%"

echo Server       : %SVR%
echo Database     : %DB%
echo Command      : %Command% %Parameter%
echo UserId       : %UserId%
echo Password     : %Password%

Syntax:

MySqlBatch.bat [SVR=ServerName] [DB=Database] [Command=value] [Parameter=value] [UserId=value] [Password=value]

Example:

MySqlBatch.bat SVR=local DB=SampleDB UserId=sa Password=Test1234

Further details at Split string with string as delimiter. Pay attention to the comment at such an answer...

Aacini
  • 65,180
  • 12
  • 72
  • 108
0

I have create batch file with named and optional parameters.

@echo off
setlocal
set SVR=%1
set DB=%2


set uid=
set pwd=
set CM=
set CP=

:loop
IF NOT "%1"=="" (
    IF "%1"=="-SVR" (
        SET SVR=%2
        SHIFT
    )
    IF "%1"=="-DB" (
        SET DB=%2
        SHIFT
    )

    IF "%1"=="-UserId" (
        SET uid=%2
        SHIFT
    )
    IF "%1"=="-Password" (
        SET pwd=%2
        SHIFT
    ) 
    IF "%1"=="-Command" (
        SET CM=%2
        SHIFT
    )
    IF "%1"=="-Parameter" (
        SET CP=%2
        SHIFT
    )
    SHIFT
    GOTO :loop
)

echo Server       : %SVR%
echo Database     : %DB%

echo Command      : %CM% %CP%

echo UserId : %uid%
echo Password : %pwd%

Syntax:

MyTestSqlBatch.bat -SVR [ServerName] -DB [Database] -Command [value] -Parameter [value] -UserId [value] -Password [value]

Example:

MyTestSqlBatch.bat -SVR local -DB SampleDB -UserId sa -Password Test1234
Jagadeesh
  • 1,630
  • 8
  • 24
  • 35