Is there a way to pass parameters “by name” (and not by order) to a batch .bat file?

前端 未结 9 1808
情话喂你
情话喂你 2021-01-30 20:35

I need to be able to pass parameters to a windows batch file BY NAME (and NOT by order). My purpose here is to give end user the flexibility to pass parameters in any order, and

9条回答
  •  半阙折子戏
    2021-01-30 21:12

    Yeah you could do something like that though I don't think you can use "=" as a token delimiter. You could use say a colon ":", somebatchfile.bat "SOURC:originalFile.txt" "TARGET:newFile.txt". Here is an example of how you might split the tokens:

    @echo off
    
    set foo=%1
    echo input: %foo%
    
    for /f "tokens=1,2 delims=:" %%a in ("%foo%") do set name=%%a & set val=%%b
    
    echo name:  %name%
    echo value: %val%
    

    Running this would produce this:

    C:\>test.bat SOURC:originalFile.txt
    input: SOURC:originalFile.txt
    name:  SOURC
    value: originalFile.txt
    

    [Edit]

    Ok, maybe it was too close to bed time for me last night but looking again this morning, you can do this:

    @echo off
    
    set %1
    set %2
    
    echo source: %SOURCE%
    echo target: %TARGET%
    

    Which would produce this (note that I reversed the source and target on the command line to show they are set and retrieved correctly):

    C:\>test.bat "TARGET=newFile.txt" "SOURCE=originalFile.txt"
    source: originalFile.txt
    target: newFile.txt
    

    Note that %1 and %2 are evaluated before the set so these do get set as environment variables. They must however be quoted on the command line.

提交回复
热议问题