0

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?

Squashman
  • 13,649
  • 5
  • 27
  • 36
Twonky
  • 796
  • 13
  • 31
  • 2
    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... I also suggest you to review [this answer](https://stackoverflow.com/questions/34987885/what-are-the-errorlevel-values-set-by-internal-cmd-exe-commands/34987886#34987886) – Aacini Dec 01 '17 at 13:54
  • @Aacini : great, that's it. If you'd make your hint an answer, I could accept it! – Twonky Dec 01 '17 at 14:11
  • 2
    If you open up a cmd prompt and read the help for the `IF` command you can also use this style of error checking. `IF ERRORLEVEL 1 ECHO We got a PROBLEM.` – Squashman Dec 01 '17 at 14:54

2 Answers2

1

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

Aacini
  • 65,180
  • 12
  • 72
  • 108
0

The help output on running in a command prompt window if /? and the old Microsoft support article Testing for a Specific Error Level in Batch Files explain 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 10 Fall Creators Update.

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.

I recommend to see also the Stack Overflow pages:

Mofi
  • 46,139
  • 17
  • 80
  • 143