我有以下bat文件mybat.bat:
1)停止服务
2)删除一些日志文件
3)再次启动服务:
@echo off
net stop "myservice"
if ERRORLEVEL 1 goto error
exit
:error
echo There was a problem...maybe it was alreay stopped
rem sometimes the terminal simply closes when trying to delete the logfiles :-(
set folder="C:\stuff\logs"
del %folder%\*.* /s /f /q
net start "myservice"
if %errorlevel% == 2 echo Could not start service.
if %errorlevel% == 0 echo Service started successfully.
echo Errorlevel: %errorlevel%
我手动打开cmd.exe实例并运行mybat.bat,但有时它只是在尝试删除日志文件时关闭,并且不会删除stuff \ logs的内容。关于为什么会发生这种情况的任何想法,以及如果删除失败,如何使cmd实例保持活动状态?
如果我等一段时间再次执行mybat,它通常会有效。
答案 0 :(得分:2)
我看到一些问题。最大的问题是,你知道你在停止服务的地方有exit
吗?您是否打算改为goto :label
呢?
另外,请尝试将引号从set folder=
行移至del %folder%
行,如下所示:
set folder=C:\stuff\logs
del /s /f /q "%folder%\*.*"
或者,也要删除子文件夹,
set folder=C:\stuff\logs
rmdir /q /s "%folder%" && md "%folder%"
在这里,试试这个。
@echo off
net stop "myservice" || echo There was a problem...maybe it was alreay stopped
:: Now that "exit" is gone, the console probably won't close any more.
set folder=C:\stuff\logs
rmdir /q /s "%folder%" && md "%folder%"
net start "myservice"
:: "if ERRORLEVEL x" checks if %errorlevel% is greater than or equal to x
if ERRORLEVEL 1 (
echo Could not start service.
) else (
echo Service started successfully.
)
echo Errorlevel: %errorlevel%
注意:net start "myservice"
代码可以像这样压缩:
:: (leave the carat in the emoticon. It escapes the parenthesis.)
(net start "myservice" && echo Great success.) || echo Fail. :^(
echo Errorlevel: %errorlevel%
有关详细信息,请参阅conditional execution。