Your Ad Here

Friday, June 4, 2010

Parsing Command Line Argument with Batch Files

On the site Computer Science 101 with Erik Oosterwal a method is described for simulating a WHILE loop in a batch file in order to parse all the parameters passed in to the batch file as command line arguments.  Here is a copy of the small amount of sample code highlighted in that article:


::     Process all the arguments from the command line
::
:_PROCESS_ARGUMENTS
    IF (%1)==() GOTO:_WRAP_TOP_DIRECTORY_IN_DOUBLE_QUOTES
    SET _Temp_Var=%1
    IF /I (%_Temp_Var:~0,2%)==(-H) GOTO:_INSTRUCTIONS
    IF /I (%_Temp_Var:~0,2%)==(/H) GOTO:_INSTRUCTIONS
    IF /I (%_Temp_Var:~0,2%)==(-?) GOTO:_INSTRUCTIONS
    IF /I (%_Temp_Var:~0,2%)==(/?) GOTO:_INSTRUCTIONS
    IF /I (%_Temp_Var:~0,2%)==(-A) SET Overwrite_File=NO
    IF /I (%_Temp_Var:~0,3%)==(-I:) SET Include_Directory=%_Temp_Var:~3%
    IF /I NOT (%_Temp_Var:~0,1%)==(-) SET Output_File="%~f1"
    SHIFT
    GOTO:_PROCESS_ARGUMENTS

:_WRAP_TOP_DIRECTORY_IN_DOUBLE_QUOTES
    IF (%Include_Directory%)==() GOTO:_INSTRUCTIONS


The original article, Parsing Command Line Parameters, includes a detailed description of how the loop works, how the parameters are evaluated, and a batch file that uses this code to create an include-file for a whole directory tree.

No comments: