Gabriel
Gabriel

Reputation: 169

How do I skip an iteration in a loop if it throws an error?

I am working in Windows 7 cmd. I wrote a couple of lines of code to copy certain files from a pretty big directory tree. Here is the code:

for /f "tokens=*" %a in ('dir "L:\Level1\Level2\Level3\\\*." /ad /b') do robocopy "L:\Level1\Level2\Level\%a\Level5\Level6\Level7" "c:\Destination\%a" /E /V /R:1 /W:1 /MT:32 /SEC

Basically, this goes into all Level4 folders (within Level3) and copies the files found in the rest of the directory.

The issue I am experiencing is that some of my Level4 folders don't actually have the Level5/Level6/Level7 path. So every time the loop gets to one of these folders, it crashes the loop.

I'd like to modify the above code so that I the loop will simply skip any folders that are causing errors, and continue on to the next.

I am running this on cmd command line. Not batch.

I know very little to no cmd code. Therefore, I would appreciate if your answer explains clearly what the syntax of the modifications should be. I know the solution is related to "errorlevel" but I am clueless as to how to implement.

Upvotes: 1

Views: 154

Answers (1)

JosefZ
JosefZ

Reputation: 30103

Check the robocopy source folder presence using if exist as follows:

for /f "tokens=*" %a in ('dir "L:\Level1\Level2\Level3\\\*." /ad /b') do if exist "L:\Level1\Level2\Level\%a\Level5\Level6\Level7\nul" robocopy "L:\Level1\Level2\Level\%a\Level5\Level6\Level7" "c:\Destination\%a" /E /V /R:1 /W:1 /MT:32 /SEC

In more readable form:

for /f "tokens=*" %a in ('dir "L:\Level1\Level2\Level3\\\*." /ad /b') do ^
  if exist "L:\Level1\Level2\Level\%a\Level5\Level6\Level7\nul" ^
    robocopy "L:\Level1\Level2\Level\%a\Level5\Level6\Level7" ^
             "c:\Destination\%a" /E /V /R:1 /W:1 /MT:32 /SEC

Note the folder\nul condition.

NUL is a file-like object which exists in any existing folder...

Upvotes: 3

Related Questions