批处理文件在满足输入条件之前退出

时间:2015-08-04 16:41:00

标签: batch-file if-statement recursion directory explorer

我创建了一个批处理文件,右键单击资源管理器并询问用户是否有文件夹名称。如果文件夹已经存在,我想继续询问用户,直到输入一个不存在的文件夹。如果文件夹已经存在,文件在两次运行后退出,我无法弄清楚为什么会发生这种情况。它看起来像它应该不断调用main,直到它获得一个不存在的文件夹名称。见下面的代码

set verbose=NO
@echo off

set mydir = %cd%
cd %mydir%
cls

call:main
echo returned from main
pause
goto:eof

:main
set /p job=Enter Job Name:
echo %job%
call:check
echo returned from check
if choice==1 call:main
echo returned from main
pause
if choice==2 call:createDirectory

:check
if exist %job% (echo Folder already exists set choice=1) else (set choice=2)
echo %choice%



:createDirectory
md "%job%"

md "%job%"\1.Development
md "%job%"\1.Development\1.Budgets
md "%job%"\1.Development\2.Manufacturers

md "%job%"\"2.Plans and Specs"
md "%job%"\"2.Plans and Specs"\1.Plans
md "%job%"\"2.Plans and Specs"\2.Specs

md "%job%"\3.Pricing
md "%job%"\3.Pricing\1.Quotes
md "%job%"\3.Pricing\2.Worksheets

md "%job%"\4.Sumbittals
md "%job%"\4.Sumbittals\"1.Submittal Reviews"

md "%job%"\5.Orders
md "%job%"\5.Orders\"1.Order Summaries"
md "%job%"\5.Orders\"2.Confirmation Pages"

md "%job%"\6.Closeout
md "%job%"\6.Closeout\"1.O&M Manuals"
md "%job%"\6.Closeout\2.Warranty

1 个答案:

答案 0 :(得分:0)

  1. check子例程不会返回给调用者,而是继续到批处理文件的末尾,在exit /b之后添加echo %choice%
  2. main子例程中:在下一个标签前添加goto main以使其循环
  3. 您正在递归调用:main,使用goto main而不使用冒号:if choice==1 goto main但实际上由于上面的#2,您不需要此行
  4. 使用&在一行中分隔命令:(echo Folder already exists & set choice=1)
  5. 使用%variable%获取其值:if %choice%==2 call :createDirectory
  6. 以下是:main:createDirectory之间更改的代码:

    :main
    set /p job=Enter Job Name:
    call:check
    if %choice%==2 call :createDirectory
    goto main
    
    :check
    if exist %job% (echo Folder already exists & set choice=1) else (set choice=2)
    exit /b