Batch file and DEL errorlevel 0 issue

前端 未结 7 662
刺人心
刺人心 2020-12-03 23:32

The batch has to remove files and directories from specific locations and output success or stdout/stderr messages to a new .txt file. I have created the most of the script

7条回答
  •  难免孤独
    2020-12-04 00:27

    IF ERRORLEVEL 0 [cmd] will execute every time because IF ERRORLEVEL # checks to see if the value of ERRORLEVEL is greater than or equal to #. Therefore, every error code will cause execution of [cmd].

    A great reference for this is: http://www.robvanderwoude.com/errorlevel.php

    >IF /?
    Performs conditional processing in batch programs.
    
    IF [NOT] ERRORLEVEL number command
    IF [NOT] string1==string2 command
    IF [NOT] EXIST filename command
    
      NOT               Specifies that Windows should carry out
                        the command only if the condition is false.
    
      ERRORLEVEL number Specifies a true condition if the last program run
                        returned an exit code equal to or greater than the number
                        specified.
    

    I would recommend modifying your code to something like the following:

    :delete
    echo deleting %1
    del /f /q c:\Users\newuser\Desktop\%1 
    if errorlevel 1 (
        rem This block executes if ERRORLEVEL is a non-zero
        echo failed
    ) else (
        echo succesful
    )
    
    GOTO :EOF
    

    If you need something that processes more than one ERRORLEVEL, you could do something like this:

    :delete
    echo deleting %1
    del /f /q c:\Users\newuser\Desktop\%1 
    if errorlevel 3 echo Cannot find path& GOTO :delete_errorcheck_done
    if errorlevel 2 echo Cannot find file& GOTO :delete_errorcheck_done
    if errorlevel 1 echo Unknown error& GOTO :delete_errorcheck_done
    echo succesful
    :delete_errorcheck_done
    
    GOTO :EOF
    

    OR

    :delete
    echo deleting %1
    del /f /q c:\Users\newuser\Desktop\%1 
    goto :delete_error%ERRORLEVEL% || goto :delete_errorOTHER
    
    :delete_errorOTHER
    echo Unknown error: %ERRORLEVEL%
    GOTO :delete_errorcheck_done
    :delete_error3
    echo Cannot find path
    GOTO :delete_errorcheck_done
    :delete_error2
    echo Cannot find file
    GOTO :delete_errorcheck_done
    :delete_error0
    echo succesful
    :delete_errorcheck_done
    
    GOTO :EOF
    

提交回复
热议问题