【问题标题】:Batch set a var not always working in loop批量设置一个 var 并不总是在循环中工作
【发布时间】:2017-05-23 20:20:49
【问题描述】:

有时我的调用 :GetTime 过程有时不起作用。 有时我的档案被命名为 .rar 而不是例如 23.05.2017_22-02-07.rar

为什么会这样?大多数时候它工作正常....

    for /f "usebackq delims=" %%a in (`"%MD5% default_main_GlobalData.CSF"`) do set StartMD5=%%a
    for %%a in (%StartMD5%) do set StartMD5=%StartMD5:~0,32%
    :Proc1
    if exist del "%Workdir%\SniperGhostWarrior3_Savegames\Hidden\.rar"
    if exist del "%Workdir%\SniperGhostWarrior3_Savegames\Profile\.rar"
    for /f "usebackq delims=" %%a in (`"%MD5% default_main_GlobalData.CSF"`) do set CurrentMD5=%%a
    for %%a in (%CurrentMD5%) do set CurrentMD5=%CurrentMD5:~0,32%
    if not "%CurrentMD5%" == "%StartMD5%" (
    call :GetTime
    %Winrar% a -inul "%Workdir%\SniperGhostWarrior3_Savegames\Hidden\Temp.rar" "C:\Users\Administrator\Saved Games\Sniper Ghost Warrior 3\"
    %Winrar% a -inul "%Workdir%\SniperGhostWarrior3_Savegames\Profile\Temp.rar" "D:\Spiele\Sniper Ghost Warrior 3\win_x64\Profile"
    ren "%Workdir%\SniperGhostWarrior3_Savegames\Hidden\Temp.rar" "%CurrentTime%.rar" >nul 2>&1
    ren "%Workdir%\SniperGhostWarrior3_Savegames\Profile\Temp.rar" "%CurrentTime%.rar" >nul 2>&1
    set "StartMD5=%CurrentMD5%"
    echo Game Saved. Backup created. %CurrentTime%
    )
    goto :Proc1
    :GetTime
    set "CurrentTime=%date%_%time:~0,-3%"
    set word=-
    call set CurrentTime=%%CurrentTime::=%word%%%
    goto :eof

【问题讨论】:

  • for %%a 循环有什么用?你永远不会在正文中使用它的变量%%a...而if exist del 是错误的语法——参见if /?...

标签: loops batch-file set


【解决方案1】:

在循环中,变量在循环结束时取它们的值。 如果您想在循环中使用它们,请将此行放在批处理的顶部:

SETLOCAL ENABLEDELAYEDEXPANSION

在你的循环中,像这样调用变量:

!var!

祝你好运!

【讨论】:

  • 谢谢。但是 setlocal 会导致递归深度错误。
【解决方案2】:

请查看关于delayedexpansion 的无穷无尽的文章。您在子程序中设置currenttime,但代码块中使用的currenttime 是遇到for 时的currenttime 的值,而不是由子程序更改。

最简单的方法:将call :gettime移动到if not "%CurrentMD5%" ==...之前

【讨论】:

  • 我太懒了。谢谢你,它现在工作正常我应该知道这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-05
  • 2021-06-22
  • 2016-04-14
  • 1970-01-01
  • 1970-01-01
  • 2014-08-24
相关资源
最近更新 更多