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?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Josh
  • 71
  • 1
  • 2

2 Answers2

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
)
Gepi
  • 59
  • 1
  • 2
  • 1
    The important bit here is `EnableDelayedExpansion` – Tim Abell Jul 27 '12 at 16:30
  • 1
    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"](http://stackoverflow.com/questions/38515054/errorlevel-in-for-f-command-loop-with-enabledelayedexpansion-returns-unexpected) – srage Jul 21 '16 at 23:25
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.

WildCrustacean
  • 5,896
  • 2
  • 31
  • 42
  • 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. – Josh Jun 21 '10 at 23:06
  • 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. – WildCrustacean Jun 22 '10 at 13:15