Search code examples
loopsbatch-filexcopy

Batch File - Loop using xcopy with variable number of Variables?


I'm a paralegal, and need to create folders and files for each contract that comes in. The folders will be named to only the address, and inside there will be 2 empty folders, and 2 prepared files, a DOCX and a TXT which need to be amended with the address in the name. I keep an example folder named simply "@" so that it stays at the top of the list of folders. I wrote a script to copy rename things as I need them:

xcopy "@" "$VAR1" /e /i
cd "$VAR1"
rename "Deed - Blank.docx" "Deed - $VAR1.docx"
rename "Deed Prep.txt" "$VAR1 Deed Prep.txt"
cd..

This saves some time, but so far, whenever I need to use it, I copy it into a NotePad window, then use Control+H to replace all instances of "$VAR1" with the address. I then copy the base script again, and Control+H with the new address. When I have everything, I open a Command Window to the root folder, and paste the commands. Sometimes we get 3 new contracts, sometimes 10, but things are generally picking up, so I know I need to make it a proper Loop to save a lot more time.

From searching, I now know that the pieces I need are set /p and for /l but.. I just don't know how to put the pieces together. I need to be able to input the addresses somehow, so whether it's being prompted one at a time, or all at once, or entering them in the main command, like script.bat "123 Happy St" "1600 Pennsylvania Ave" "32 John's Wall Dr" that would be much better than how I do it now.

Thanks in advance!


Solution

  • @echo off
    setlocal
    :again
    set "property=%~1"
    if not defined property goto :eof
    
    xcopy "@" "%property%" /e /i
    cd "%property%"
    rename "Deed - Blank.docx" "Deed - %property%.docx"
    rename "Deed Prep.txt" "%property% Deed Prep.txt"
    cd..
    
    shift
    goto again
    

    The first two lines 1) suppress echo ing of the commands executed to the console and 2) make sure that any changes to the environment are backed out when the batch ends. This ensures that successive batch files don't interact due to variables established in a prior batch run in the same session.

    The label again is simply a return-point (colon is required)

    the set command gets the first argument, removes its surrounding quotes, and assigns the result to the variable property.

    If there are no further arguments, property will be unassigned, so exit the batch (the colon is required)

    Then in your routine, use the value of property within the commands by surrounding the variablename with %.

    Finally, shift the arguments - discard %1 and shuffle the remained along, so %2 becomes %1, etc.

    Then you can run the batch as script.bat "123 Happy St" "1600 Pennsylvania Ave" "32 John's Wall Dr"