How to pass arguments (not command line arguments)

2019-04-07 15:44发布

问题:

I'm writing a batch file for automating the creation of typical folder structures for products that we sell. I would like to be able to call my batch file with 2 optional arguments; the name of the supplier and a file for creating lots of folders at once. If no supplier is supplied the script asks via standard input who the supplier is. If no file is supplied the script asks for the name of the folder you wish to create. If a file is passed as an argument I would like the script to read the file line by line and create a folder for each line, named after the contents of that line. Here is the :readFile function:

:readFile
    echo "Reading from file: %theFile%"
    FOR /F "delims=," %%a IN (%theFile%) do (
        call:makeFolder %%a
    )
    goto:EOF

Here is the :makeFolder function that optionally takes the argument of the name of the folder to create. If no argument is supplied it asks for the name via standard input.

:makeFolder  
    if [%1]==[] (
        set /p product="Enter product name: "
    ) else (
        set product=%1
    )
    if exist "P:\%supplier%\Products\%product%" (
        echo.
        echo The folder '%product%' already exists.
        echo.
        goto:EOF
    )
    mkdir "P:\%supplier%\Products\%product%\Images\Web Ready"
    mkdir "P:\%supplier%\Products\%product%\Images\Supplied"
    mkdir "P:\%supplier%\Products\%product%\Images\Edited"
    goto:EOF

My problem is that in the :makeFolder function %1 refers to the 1st argument given on the command line, not the one provided in the :readFile function. How can I achieve this? Caveat: I'm very new to batch scripting so you may have to speak to me like I'm a bit stupid.

回答1:

I rebuild the file and it worked

@echo off
set "supplier=C:\temp\supp\"
set "product=Car"
echo test1,myComment,myValue > myFile.txt
call :readFile "myFile.txt"
EXIT /B

:readFile
echo "Reading from file: %~1"
FOR /F "usebackq delims=," %%a IN ("%~1") do (
    call :makeFolder %%a
)
goto:EOF

:makeFolder  
if "%1"=="" (
    set /p product="Enter product name: "
) else (
    set "product=%1"
)
if exist "%supplier%\Products\%product%" (
    echo(
    echo The folder '%product%' already exists.
    echo(
    goto:EOF
)
echo "%1"
echo mkdir "%supplier%\Products\%product%\Images\Web Ready"
echo mkdir "%supplier%\Products\%product%\Images\Supplied"
echo mkdir "%supplier%\Products\%product%\Images\Edited"
goto:EOF

But I would recommend to use delayed expansion, as you can got problems with the percent expansion of special characters( In this case not very relevant, as special characters are a bad choice for file/directory names).