首页 > 解决方案 > 文件不断被删除

问题描述

我在使用我的批处理程序时遇到问题,其中有 2 个if语句,其中一个语句允许用户向日志文件添加注释,而另一个if语句则完全删除日志文件。

这取决于用户他们选择哪个选项,但是当我运行文件时,即使我输入选项 1 以向日志文件添加注释而不是删除它,它似乎也会删除我的日志文件。

echo loggedTime = %time% %date%>> log.txt

REM This is for the 2 scenarios the user has to choose from

echo Please make your choice:

set /p choice1=

REM This takes the user's input and adds it to the end of the text file

IF %choice1%== 1 echo Please enter your comment:

set /p comment=

echo %comment%>> log.txt

REM this deletes the log file altogether

IF %choice1%== 2 echo The log file is being deleted

cd C:\Users\.....

del log.txt

标签: batch-file

解决方案


The command interpreter reads every line in the script unless you structure your script in a way that prevents this.

This most common ways of achieving this is through the use of code blocks (Lines of code contained within parentheses) and Labels to 'skip' lines. When taking user input, through set /p, you need a method to validate it, and return for new input if the input doesn't match the Conditional tests your using.

There is a better way still to achieve all of these points, and thats combining the Choice Command with Labels in the form of subroutines as follows:

@Echo off
Goto :main
REM Script break created by the label Jump

REM Subroutines
:Choice[1]
    Echo(loggedTime = [%time% %date%]>>"%temp%\Mylog.txt"
    set /p comment=Comment:
    echo("%comment%">>"%temp%\Mylog.txt"
    Exit /B
:Choice[2]
    del "%temp%\Mylog.txt"
    Exit /B
:Choice[3]
    IF exist "%temp%\Mylog.txt" (TYPE "%temp%\Mylog.txt")
    Exit /B

REM main body of the script
:main
REM /N : Hide options prompt
REM /C : Define options (options will be assigned errorlevel according to occurance after /C switch)
REM /M "prompt string" : Define Custom prompt for the choice
    CHOICE /N /C cdv /M "add (C)omment (D)elete Log (V)iew Log"
REM Calls the selected subroutine. Exit /B within the Subroutine resumes the script from after the call
    CALL :Choice[%errorlevel%]
    pause
    Exit /B

推荐阅读