

Rem this is the corrected ErrorLevel query: Rem this line constitutes the work-around:įor /F "tokens=*" %%# in ('del /F /Q "C:\Users\newuser\Desktop\%~1" 2^>^&1 1^> nul') do (2> nul set =) Rem this line resets ErrorLevel initially: The following batch file demonstrates how the above described work-around could be applied: :DELETE It might be a bit worse in terms of performance though. For sure it is more flexible because you can state any (signed 32-bit) number, including 0 to clear it (omitting the number clears it as well). To set the ErrorLevel explicitly you could also use cmd /C exit /B 1.

The 2> nul portion avoids the message The syntax of the command is incorrect. If for /F recieves any STDERR output from the del command line, the command in the loop body is executed, which is set = this is an invalid syntax, therefore set sets the ErrorLevel to 1. Notice that ErrorLevel will not be reset in that case, its value remains unchanged. If the deletion was successful, del does not generate a STDERR output, hence the for /F loop does not iterate, because there is nothing to parse. By the part 2>&1 1> nul, the command output at STDOUT will be dismissed, and its STDERR output will be redirected so that for /F receives it. This executes the command line del /F /Q "\path\to\the\file_s.txt". If you do want prompts (in case wildcards ? and/or * are present in the file path), remove /Q. If you do not want to delete read-only files, remove /F from the del command line
#CMD C EXIT CODE#
To use the code in command prompt directly rather than in a batch file, write %# instead of %%#. Possible Work-AroundĪ possible work-around is to capture the STDERR output of del, because in case of deletion errors, the related messages ( Could Not Find, Access is denied., The process cannot access the file because it is being used by another process.) are written there.

#CMD C EXIT WINDOWS#
The del command does not set the ErrorLevel as long as the given arguments are valid, it even resets the ErrorLevel to 0 in such cases (at least for Windows 7).ĭel modifies the ErrorLevel only in case an invalid switch is provided ( del /X sets ErrorLevel to 1), no arguments are specified at all ( del sets ErrorLevel to 1 too), or an incorrect file path is given ( del : sets ErrorLevel to 123), at least for Windows 7.
