1

I don't think that my question is duplicate to batch: Exit code for "rd" is 0 on error as well because I've tried everything from that answer and it didn't help (as you can see on screenshots below).

Let's say I want to delete directory with files in it. But I don't want script to continue executing in case of an error. So I tried to:

ECHO 3. Deleting Client index folder which will be rebuilt if it actually exist...
rmdir /S /Q "XXX"
ECHO %ERRORLEVEL%
IF %ERRORLEVEL% NEQ 0 ECHO Failed to delete client index folder... & GOTO :End

But %ERRORLEVEL% variable was always equal 0. enter image description here

Then I found similar questions on Stackoverflow and changed script to this:

ECHO 3. Deleting Client index folder which will be rebuilt if it actually exist...
rmdir /S /Q "XXX" && echo OK || echo ERROR
ECHO %ERRORLEVEL%
IF %ERRORLEVEL% NEQ 0 ECHO Failed to delete client index folder... & GOTO :End

And it worked well! enter image description here

But the problem is that I want script to continue working if folder doesn't exist (i.e. was already deleted). With that implementation it wasn't working. enter image description here

So I changed script like this:

ECHO 3. Deleting Client index folder which will be rebuilt if it actually exist...
if exist "XXX" (rmdir /S /Q "%4_%5" && echo OK || echo ERROR)
ECHO %ERRORLEVEL%
IF %ERRORLEVEL% NEQ 0 ECHO Failed to delete client index folder... & GOTO :End

Aaaaaaaand it stopped setting up %ErrorLevel% variable again in case of file lock... enter image description here

I've tried to remove brackets after "exist" condition. Tried to change "if exist" to "2>nul", but none of these options work as I need. Any suggestions on how I should fix it?

Rudean
  • 255
  • 3
  • 13
  • 1
    Note that in your situation, [rychu's answer](https://stackoverflow.com/a/29562902/886887) provides a much easier workaround. `if exist xxx rd /s /q xxx` then `if exist xxx echo Oops` then `if exist xxx goto :End` concise and easy to understand. – Harry Johnston Sep 30 '17 at 00:12
  • 1
    Note also that there is an issue in Windows that sometimes causes the first `rd` to fail at random. You can resolve this by repeating the first line, i.e., `if exist xxx rd /s /q xxx` followed by `if exist xxx rd /s /q xxx` and then check for an error. Doing it twice looks redundant, but it *will* make it more reliable. – Harry Johnston Sep 30 '17 at 00:14
  • Dude you are my savior. Yeap, first option with trying to delete directory and "if exist" check afterwards seems nice and clean! Thank you! – Rudean Oct 02 '17 at 07:43
  • First, rd (rmdir) works partially for errno 32 (file in being used by another process) that is works only if /s flag is not used. Second, it does not work at all for errno 5 (access denied) if this "access denied" comes from some file inside the target directory. See comments under https://stackoverflow.com/a/11137825/4807875. – Alexander Samoylov Nov 16 '18 at 16:09

0 Answers0