【问题标题】:cmd terminates when delete fails删除失败时 cmd 终止
【发布时间】:2013-04-16 18:15:39
【问题描述】:

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

【问题讨论】:

  • 我无法回答一个不断变化的问题 :-(
  • 以上是最终版本:-)

标签: windows-7 batch-file


【解决方案1】:

我发现了一些问题。最大的问题是,您知道在您停止服务的位置下方有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 了解更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-04
    • 2022-07-21
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    • 2023-01-04
    相关资源
    最近更新 更多