批处理文件:使用IF子句

时间:2016-05-17 19:23:57

标签: windows batch-file cmd batch-processing

一开始:我为我糟糕的英语和拼写错误道歉,我是这个论坛的新手,如果我做错了,请随意指出,我刚刚开始编程所以我就是什么叫做菜鸟;)

我有一个非常具体的问题。我正在尝试编写一个批处理文件来为游戏安装服务器,我必须下载大约三个文件。为此,我使用bitsadmin命令,但有时下载失败,我希望批处理删除这个错误文件,如果失败则再次下载。

以下是使用过的代码片段之一:

rem Download SteamCMD

:cmd_not_exist

>>%directory%RustServer\temp\log1.txt bitsadmin /transfer Download_SteamCMD 
/download /priority normal https://steamcdn-a.akamaihd.net/client/installer/steamcmd.zip %directory%SteamCMD\steamcmd.zip

set "do_cmd_exist="

for /F "skip=8 delims=" %%i in (>>%directory%RustServer\temp\log1.txt) do if not defined do_cmd_exist set "do_cmd_exist=%%i"

if "%do_cmd_exist%" == "Transfer complete." ( 

    goto cmd_exist

) else (

    del %directory%SteamCMD\steamcmd.zip

    del %directory%RustServer\temp\log1.txt

    goto cmd_not_exist

)

:cmd_exist

(没有自由线看起来真的搞砸了)

所以我正在尝试编写命令日志并检查日志以查看它是否显示传输完成。但它没有用。

我对任何建议持开放态度,但我不喜欢使用第三方合作伙伴计划。

要查看所有代码 - 我将它放在我的Pastebin页面上。 http://pastebin.com/w7wLsvkF

感谢您花时间阅读此内容... xD

1 个答案:

答案 0 :(得分:0)

虽然我无法证明bitsadmin命令行的正确性,但下一个注释的代码段可以帮助解析日志文件:

@ECHO OFF
SETLOCAL EnableExtensions

set "directory=define variable `directory` with no double quotes here" 

rem for better readability and to avoid typo mistakes
set "_log_file=%directory%RustServer\temp\log1.txt"
set "_zip_file=%directory%SteamCMD\steamcmd.zip"
set "_switches=/transfer Download_SteamCMD /download /priority normal"
set "_zip__URL=https://steamcdn-a.akamaihd.net/client/installer/steamcmd.zip"

rem Download SteamCMD

:cmd_not_exist
rem let user watch batch progress
echo %date% %time% attempt to download
>"%_log_file%" bitsadmin %_switches% %_zip__URL% "%_zip_file%"

set "do_cmd_exist="
for /F "tokens=*" %%i in ( 'findstr /i /C:"Transfer complete." "%_log_file%"'
                         ) do if not defined do_cmd_exist set "do_cmd_exist=%%i"

if defined do_cmd_exist (
    rem let user watch batch progress
    echo %date% %time% %do_cmd_exist%
    goto cmd_exist
) else (
    del "%_zip_file%"
    del "%_log_file%"
    goto cmd_not_exist
)
:cmd_exist

错误 mea culpa ):请比较for /F Loop command: against the results of another command.

for /F "tokens=*" %%i in ( 'findstr /i /C:"Transfer complete." "%_log_file%"'
rem forgot apostrophes     ^ here                                  and here ^

资源(必读):