【问题标题】:if exist not functioning in .BAT file如果存在在 .BAT 文件中不起作用
【发布时间】:2017-01-25 12:39:56
【问题描述】:

我正在尝试创建一个仅在文件 Startapp.bat 退出时运行和复制内容的 .Bat 文件。这个 startapp 文件是用户在 github 上提交代码时创建的。

我有以下脚本。

taskkill /F /IM Webshop.exe

::%~dp0 means the current folder where this .bat is executed from
SET dest=%~dp0productionEnv

IF EXIST "%~dp0startApp.bat" (
    if not exist "%dest%" mkdir "%dest%" 
    xcopy /Y /s "%~dp0Webshop\bin\Debug" "%dest%"
    SET webDest="%dest%/webContent"

    if not exist %webDest% mkdir %webDest% 
    xcopy /Y /s "%~dp0Webshop\webContent\web" %webDest%
    copy /Y "%~dp0startApp.bat" "%dest%/startApp.bat"
    START "" "%dest%/startApp.bat"
    del "%~dp0startApp.bat"
    echo "Deleted startApp.bat"

) ELSE (
    echo "startApp.bat file not found"
)

但它不起作用。有时它会同时回显已删除的消息和未找到文件的消息,而这是不可能的。它应该回显这些消息中的任何一个,但不能同时回显这两个消息。这就是为什么会有 if else 的原因。

请帮忙!

【问题讨论】:

  • 您在代码块中设置变量,文件路径在 Windows 中通常使用反斜杠
  • echo "%~dp0startApp.bat" 的结果是什么?
  • 您在哪个环境下工作? Pre-XP OS 对“IF EXIST”有不同的处理方式。
  • 关键是delayed expansion,因为您正在编写读取同一个带括号的代码块中的变量。对于 Windows cmd 中的路径,请始终使用 \ 作为分隔符。

标签: windows batch-file


【解决方案1】:

这里是相同的东西,正斜杠固定和不必要的 if 块改变:

Taskkill /F /IM Webshop.exe

If Not Exist "%~dp0startApp.bat" (
    Echo= startApp.bat file not found
    GoTo Next
)

Rem %~dp0 means the current folder where this .bat is executed from
Set "dest=%~dp0productionEnv"
Set "webDest=%dest%\webContent"

If Not Exist "%dest%" MD "%dest%"
XCopy "%~dp0Webshop\bin\Debug" "%dest%" /Y /S
If Not Exist "%webDest%" MD "%webDest%"
XCopy "%~dp0Webshop\webContent\web" "%webDest%" /Y /S
Copy /Y "%~dp0startApp.bat" "%dest%"
Call "%dest%\startApp.bat"
Del "%~dp0startApp.bat"
Echo= Deleted startApp.bat

:Next

【讨论】:

    【解决方案2】:

    我不确定代码中是否还有更多错误,但我至少发现了一个:

    SET webDest="%dest%/webContent"
    
    if not exist %webDest% mkdir %webDest%
    

    所以如果文件夹不存在,你正在执行这一行:

    mkdir %webDest%
    

    其中%webDest%"%dest%/webContent" 表示%~dp0productionEnv/webContent

    此行会导致错误。在 Windows 中的路径字符串中有两个可能的分隔符:正确的一个是 \,而错误的一个(但支持)/\ 来自 DOS 和 windows,/ 来自 UNIX。虽然 Windows 通常足够聪明,可以解析您的命令,甚至允许您混淆 \/,但 mkdir 命令不允许这样做。

    这意味着:mkdir C:\some\folder 可以工作,但 mkdir C:/some/foldermkdir C:\some/folder 不会。

    编辑:同样适用于xcopy/ 之后的所有内容都被视为参数,而不是路径的一部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-14
      • 2021-11-16
      • 2021-12-21
      • 1970-01-01
      • 2013-12-11
      • 2011-06-12
      相关资源
      最近更新 更多