如何将参数(不是命令行参数)传递给批处理脚本中的函数

时间:2011-10-24 14:49:25

标签: batch-file command-line-arguments argument-passing

我正在编写一个批处理文件,用于自动创建我们销售的产品的典型文件夹结构。我希望能够使用2个可选参数调用我的批处理文件;供应商的名称和一次创建大量文件夹的文件。如果没有提供供应商,则脚本通过标准输入询问供应商。如果未提供文件,则脚本会询问您要创建的文件夹的名称。如果文件 作为参数传递,我希望脚本逐行读取文件并为每行创建一个文件夹,以该行的内容命名。这是:readFile函数:

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

这是:makeFolder函数,可选择接受要创建的文件夹名称的参数。如果没有提供参数,它会通过标准输入询问名称。

: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

我的问题是:makeFolder函数%1是指命令行中给出的第一个参数,而不是:readFile函数中提供的参数。我怎样才能做到这一点?警告:我是非常批处理脚本的新手,所以你可能不得不跟我说话,好像我有点傻。

1 个答案:

答案 0 :(得分:10)

我重建文件并且有效

@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

但我建议使用延迟扩展,因为你可能会遇到特殊字符扩展百分比的问题(在这种情况下不是很相关,因为特殊字符是文件/目录名称的错误选择)。

相关问题