tags:

views:

66

answers:

1

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?

+1  A: 

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.

bde
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
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.
bde