0

我有以下 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 它通常可以工作。

4

1 回答 1

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%

有关更多信息,请参阅条件执行

于 2013-04-16T19:34:11.433 回答