在批处理文件中使用多个命令循环

时间:2017-08-02 10:03:09

标签: windows batch-file

我正在尝试使用多行for循环而没有成功 - 代码似乎爆炸了。我已经启用了EnableDelayedExpansion,但这似乎没有帮助:-(代码似乎在“echo start for loop”之后退出。

任何想法,为什么这不起作用将非常感激: - )

谢谢,海伦。

:: script to rename tv/radio folders with issue date.

@echo off
:: All vars set in this file will be local:
SETLOCAL
setlocal EnableDelayedExpansion

:SetDate
echo.
set /P NewDate=Please enter date to rename to (yymmdd) or "x" to exit:
echo.
echo new date = %NewDate%
:: Loop to user input until a character is entered:
if "%NewDate%"=="" GOTO Error
If "%NewDate%"=="x" GOTO Exit
:: User has entered a value so confirm it is correct.
GOTO ConfirmDate

:ConfirmDate
echo.
set /P Confirmation=Is this date correct? (y/n):
echo.
echo confirmation = %Confirmation%
if "%Confirmation%"=="y" GOTO RenameFolders
:: Else
GOTO SetDate

:RenameFolders
:: for each folder name containing "xxx", replace "xxx" with the new date
echo.
echo start for loop
for /D %%D in ("?xxx*") do (
    set "PDIR=%%~fD" & set "NAME=%%~nxD"
    echo check whether folder exists
    if EXIST "!NAME:xxx=%NewDate%!" (
        echo.
        echo folders already exist! - remove them and try again!
        GOTO :End
    ) ELSE (
        move "!PDIR!" "!NAME:xxx=%NewDate%!"
    )
)
echo.
echo Folder rename is complete. Thank you.
GOTO End

:Error
echo.
echo You did not enter a date!!
GOTO SetDate

:Exit
echo.
echo User requested exit, bye bye!
GOTO End

:End
::Remember to end command for local vars:
ENDLOCAL
:: exit script

2 个答案:

答案 0 :(得分:0)

据我所知,当没有任何目录存在时,你的for循环没有任何问题。

问题在于,当找到现有目录时,您已经专门指示代码GOTO :End,这会使“打破”循环。

您必须决定如何在现有目录名称的情况下采取最佳行动,并相应地更改您的代码。

答案 1 :(得分:0)

感谢各位的帮助: - )

我发现问题的根源......某种程度上包含" xxx"已从源/目录目录中删除,因此for循环没有任何工作,但由于回声已关闭,可能是我错过了一条消息,可能导致我更快地弄清楚这一点!卫生署!多么愚蠢的错误:-(我下次试着不要这么快就跳枪......

谢谢,海伦。