7

The following code always displays 0 as the errorlevel, but when the copy command is done outside of the for loop command it returns a non zero errorlevel.

for /f "usebackq delims=" %%x in (`copy x y`) do (
    set VAR=%%x
)
ECHO Errorlevel = %ERRORLEVEL%
ECHO VAR = %VAR%

Is is possible to get the errorlevel of the copy command executed by the for loop?

2 Answers 2

5

it works for me ! You only need to put the error checking within the DO parentheses with a text file containing the copy commands (7200 lines; for example: copy 2_97691_Scan.pdf O:\Data\Dev\Mins\PDFScan2\2011\4\2_97691_Scan.pdf), I can run the following batch file

@echo off

setlocal EnableDelayedExpansion

for /F "delims=" %%I in (CopyCurrentPDFs.txt) do (
%%I
if !errorlevel! NEQ 0 echo %%I>>errorcopy.txt
)
Sign up to request clarification or add additional context in comments.

2 Comments

The important bit here is EnableDelayedExpansion
Warning: this is a solution for a FOR /F file loop, not a FOR /F command loop as per the original question. Please see: "ERRORLEVEL in FOR /F Command Loop Returns Unexpected Result"
1

I am assuming that you are copying files from one directory to another? If so, you could do something like this instead:

@echo off

setlocal EnableDelayedExpansion

set ERR=0

for %%x in (x) do (

    copy %%x y
    set ERR=!errorlevel!

    set VAR=%%x
)
ECHO Errorlevel = %ERR%
ECHO VAR = %VAR%

The delayed expansion is required to get the actual value of errorlevel inside the loop instead of the value before the loop is entered.

If that isn't what you are trying to do, please clarify your objective.

2 Comments

I am trying to parse the output for an executable (the copy is just a simple example), but I want to know if that executable returned an error.
Ok. I'm not sure if you can get the errorlevel for the command executed by the for loop without separating them like in my example, maybe someone else can provide a better answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.