'RD' command not returning '0' or '1' as errorlevel on success or failure

254 views Asked by At

I am using the RD command in my batch script to remove a directory.

I assumed RD should return 0 for success, or 1 for failure. but it doesn't appear to do so.

I am using the Robocopy command utility before the RD command, and its taking the Errorlevel from Robocopy instead.

Please advise the exact exit codes RD returns for success and failure.

robocopy src target ...
rd /S /Q %Target%
IF  %ERRORLEVEL% EQU 0  goto :good
IF  %ERRORLEVEL% NEQ 0  goto :fail
2

There are 2 answers

3
Magoo On

Your assumption is incorrect.

@ECHO OFF
SETLOCAL

MD hit
RD hit
ECHO %errorlevel%
RD miss
ECHO %errorlevel%

GOTO :EOF
5
Aacini On

Yes, the RD command have a "funny" way to return error codes. Basically, you just need to add || REM command after the RD in order to correctly "set" the ERRORLEVEL value on errors (the ERRORLEVEL is not modified when it works correctly):

robocopy src target ...
rd /S /Q %Target% || rem
IF  %ERRORLEVEL% EQU 0  goto :good
IF  %ERRORLEVEL% NEQ 0  goto :fail

These are the error values returned by RD command this way:

1 = Bad switch given
2 = Directory not found
5 = Access denied
32 = Directory in use
145 = Directory not empty.

This behavior is described with detail below Table 5 header at this answer about "Errorlevel values set by internal commands"