根据批处理代码创建用户输入日志

时间:2018-08-02 19:05:09

标签: windows batch-file cmd

我有一个Windows批处理脚本,该脚本是我从Google搜索中整理而来的。我最近一次找到我需要的东西的过程很复杂。我希望有人能提供帮助。

最近,我的一位用户发誓我的脚本会在没有他们输入的情况下为他们打开和关闭。我个人认为这不太可能,因为任何企图目睹“错误”的尝试都是不可能的,而且多年来,此脚本已完美地满足了我们的需求。

我想添加代码以在批处理运行时创建任何用户输入的output.log。如果用户在空提示下按ENTER键,我期望输出包含y,n或空/ nul。

由于业务安全限制,我只能使用批处理脚本,因此,如果这不可能,那么我将不得不另辟other径。

有人会审核并告诉我如何添加必要的代码,以实现我所需要的吗?

谢谢。

@echo off

SET /P ANSWER=Have checks been deposited and daily balance file saved (Y/N)?
echo You chose: %ANSWER%
if /i {%ANSWER%}=={y} (goto :yes)
if /i {%ANSWER%}=={yes} (goto :yes)

goto :no

:yes
for /f "tokens=1-5 delims=/ " %%d in ("%date%") do rename "DailyBalance.xlsm" %%e-%%f-%%g-Deposit.xlsm
echo File Rename Complete!
pause
move "C:\Deposit\*Deposit.xlsm" "C:\Deposit\Complete\" 
echo Renamed File Move Complete!
pause
copy "C:\Deposit\Reset\DailyBalance.xlsm" "C:\Deposit\" 
echo Daily Balance File Refreshed and ready for tomorrow!
echo Daily Backup has completed!
pause
exit /b 0

:no
echo Please run DailyBackup once the deposit has been completed.
pause
exit /b 1

1 个答案:

答案 0 :(得分:1)

下面的代码省略了一些实际工作,以便专注于流控制。我怀疑真正的问题将是确定LOGFILE的位置和名称。该代码将其命名为与.bat文件相同,但扩展名为“ .log”。

@echo off
SET "LOGFILE=%TEMP%\%~n0.log"

CHOICE /M Have checks been deposited and daily balance file saved?
ECHO>>"%LOGFILE%" Choice at %DATE% %TIME% by %USERNAME% is %ERRORLEVEL%
IF ERRORLEVEL 2 (GOTO No)

:Yes
rem ...
echo Daily Backup has completed!
pause
exit /b 0

:No
echo Please run DailyBackup once the deposit has been completed.
pause
exit /b 1

更新:

在Squashman的建议下,我包括了功能代码。我还使用了IF / ELSE而不是GOTO。此外,它还完成了文件重命名,而没有FOR循环。

@echo off
SET "LOGFILE=%TEMP%\%~n0.log"

CHOICE /M Have checks been deposited and daily balance file saved?

ECHO>>%LOGFILE% Choice at %DATE% %TIME% by %USERNAME% is %ERRORLEVEL%

IF %ERRORLEVEL% EQU 1  (
    for /f "tokens=1-5 delims=/ " %%d in ("%date%") do rename "DailyBalance.xlsm" %%e-%%f-%%g-Deposit.xlsm
    echo File Rename Complete!
    pause
    move "C:\Deposit\*Deposit.xlsm" "C:\Deposit\Complete\"
    echo Renamed File Move Complete!
    pause
    copy "C:\Deposit\Reset\DailyBalance.xlsm" "C:\Deposit\"
    echo Daily Balance File Refreshed and ready for tomorrow!
    echo Daily Backup has completed!
    SET "EXITCODE=0"
) ELSE (
    echo Please run DailyBackup once the deposit has been completed.
    SET "EXITCODE=1"
)

pause
exit /b %EXITCODE%