Twonky
Twonky

Reputation: 806

'rename' command sets ERRORLEVEL to 0, even on failure

In my batch file, I wonder why I can't create a hook for error handling if rename fails. I create a folder foo and have a shell changing its cwd to foo so that the folder should not be renamable. Then I start my script:

for %%x in (%PROGRAMFILES(X86)%") do (
    for %%y in (foo) do (
        if exist "%%~x\%%~y" (
            rename "%%~x\%%~y" _to_be_removed
            echo %ERRORLEVEL%
            IF NOT %ERRORLEVEL% EQU 0 (echo We got a problem.)
        )
    )
)

Unfortunately, I get the notification that the folder cannot be deleted because it is in use:

Der Prozess kann nicht auf die Datei zugreifen, da sie von einem anderen Prozess verwendet wird.
0

Huh? rename failed, but %ERRORLEVEL% is zero? This should not be possible, no?

Upvotes: 0

Views: 2126

Answers (2)

Mofi
Mofi

Reputation: 49167

The help output on running in a command prompt window if /? explains how to test for exit code of previous command/script/application outside a command block as well as inside a command block working from MS-DOS to currently latest Windows 11.

The solution is simply using:

if errorlevel 1 echo We got a problem.

instead of the lines

echo %ERRORLEVEL%
IF NOT %ERRORLEVEL% EQU 0 (echo We got a problem.)

It is really so easy to test if a previously executed command exited with a value greater or equal 1 indicating an error on execution instead of 0 indicating a successful execution.

It is also possible testing on a specific exit code value for Windows commands like ROBOCOPY or programs like RAR or 7-Zip by using:

if errorlevel 5 if not errorlevel 6 echo Exit code is 5.

The first condition if errorlevel 5 checks if the exit code is greater or equal 5 which means it cannot be less than 5 on this condition evaluates to true.

The second condition if not errorlevel 6 checks if the exit code is NOT greater or equal 6 which evaluates to true only on exit code is less than 6.

The exit code value greater or equal 5 AND less than 6 must be 5 to fulfill both conditions.

I recommend to see also the Stack Overflow pages:

Upvotes: 1

Aacini
Aacini

Reputation: 67256

To get a new value that change inside a (code block), you need to use this form: !errorlevel! and include setlocal EnableDelayedExpansion command at beginning; search for "Delayed Expansion" in this forum...

Upvotes: 1

Related Questions