What about more complex logic?
Assume that MyFile.txt is a list formatted as follows:
SourceDrive:\SourcePath SourceFileName TargetDrive:\TargetPath
Example:
C:\Temp File1.txt C:\Target1
C:\Foo File2.txt C:\Target2
etc.
Let's say I want to validate each element, and skip to the next iteration of the loop if
any of that validation fails.
@ECHO OFF
FOR /F "tokens=1-3" %%a IN (MyFile.txt) DO (
SET SourceDir=%%a
SET SourceFile=%%b
SET TargetDir=%%c
:ValidateSourceDir
IF NOT EXIST !SourceDir! (
ECHO Invalid Source Directory !SourceDir!
REM Loop to the next iteration
) ELSE (
ECHO Source Directory !SourceDir! Validated
)
:ValidateSourceFile
IF NOT EXIST !SourceDir!\!SourceFile! (
ECHO Invalid Source File !SourceDir!\!SourceFile!
REM Loop to the next iteration
) ELSE (
ECHO Source File !SourceDir!\!SourceFile! Validated
)
:ValidateTargetDir
IF NOT EXIST !TargetDir! (
ECHO Invalid Target Directory !TargetDir!
REM Loop to the next iteration
) ELSE (
ECHO Target Directory !TargetDir! Validated
)
:NowDoSomeOtherStuff
XCOPY !SourceDir!\!SourceFile! !TargetDir!
)
The :Labels are there simply for readability. Constructing this with nested, all-or-nothing execution is ugly, and a pain, especially as additional logic is needed.
The following looks like it
should do the trick, but it fails with, "The syntax of the command is incorrect.":
@ECHO OFF
FOR /F "tokens=1-3" %%a IN (MyFile.txt) DO (
SET SourceDir=%%a
SET SourceFile=%%b
SET TargetDir=%%c
:ValidateSourceDir
IF NOT EXIST !SourceDir! (
ECHO Invalid Source Directory !SourceDir!
REM Loop to the next iteration
GOTO NextLoop
) ELSE (
ECHO Source Directory !SourceDir! Validated
)
:ValidateSourceFile
IF NOT EXIST !SourceDir!\!SourceFile! (
ECHO Invalid Source File !SourceDir!\!SourceFile!
REM Loop to the next iteration
GOTO NextLoop
) ELSE (
ECHO Source File !SourceDir!\!SourceFile! Validated
)
:ValidateTargetDir
IF NOT EXIST !TargetDir! (
ECHO Invalid Target Directory !TargetDir!
REM Loop to the next iteration
GOTO NextLoop
) ELSE (
ECHO Target Directory !TargetDir! Validated
)
:NowDoSomeOtherStuff
XCOPY !SourceDir!\!SourceFile! !TargetDir!
:NextLoop
)
I do
not get the "incorrect syntax" error
if I add some place-holder statement after the :NextLoop tag, like this...
:NextLoop
ECHO. > NUL
...BUT, if any iteration fails -- for example, with "Invalid Source File C:\Temp\NoSuchFile.txt," the loop
terminates.
How can I loop to the next iteration of a FOR loop?btw, I have been a fan of this site for a long time, and this is my first post! Sorry about resurrecting an old post, but that serves two purposes: It shows that I've searched for a solution first, and it best illustrates the problem. Thank you for your (past and future) assistance! I hope I can contribute.
EDIT: I know, I can validate path and file name in one step, with "IF EXIST !SourceDir!\!SourceFile!," but I wanted to illustrate a multi-stage validation process.