Search code examples
batch-fileoptional-parametersnamed-parameters

Create batch file with multiple named parameters


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,


Solution

  • 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