代码之家  ›  专栏  ›  技术社区  ›  pasha

如何在批处理文件中创建依赖于其他变量(如%time%date%)的变量?

  •  0
  • pasha  · 技术社区  · 7 年前

    假设我要打印三次时间和日期,我必须写

    echo %date% %time%
    echo %date% %time%
    echo %date% %time%
    

    上面的代码打印三次,如果我将%date%%time%分配给一个变量(避免每次都写),那么它将打印三次常量值,

    set a=%date%_%time%
    echo %a%
    echo %a%
    echo %a%
    

    %a% 变量一次,并且在实际日期和时间发生更改时仍会回显。

    4 回复  |  直到 7 年前
        1
  •  2
  •   aschipfl    7 年前

    在批处理文件中该如何处理:

    set "a=%%date%% %%time%%"
    
    call echo %a%
    > nul timeout 1
    call echo %a%
    > nul timeout 1
    call echo %a%
    

    >>> set "a=%^date% %^time%"
    >>> call echo %a%
    >>> call echo %a%
    >>> call echo %a%
    
        2
  •  5
  •   Stephan    7 年前

    有可能 delayed expansion

    @echo off
    setlocal enabledelayedexpansion
    set  "a=^!time^!"
    echo %a%
    timeout 2 >nul
    echo %a%
    

    经常 call 用于第二层解析以避免延迟扩展(如 aschipfl's answer

    如果出于任何原因必须禁用延迟扩展或希望它直接在命令行上工作,则 方法是一个很好的选择,当你不介意键入额外的 命令。

        3
  •  1
  •   Gerhard    7 年前

    set a 一次,但还是显示了日期和时间的实际变化?

    @echo off
    setlocal enabledelayedexpansion
    for %%i in (1,1,3) do (
            set a=!date!_!time!
            timeout /t 1 > nul
            echo !a!
    )
    

    我使用了timeout来简单地显示时间差异,因为它运行得太快了,它将显示与毫秒内运行的时间相同的时间。

    或者,调用标签:

    @echo off
    for %%i in (1,1,3) do (
    call :timeloop
    )
    goto :eof
    :timeloop
    set a=%date%_%time%
    timeout /t 1 > nul
    echo %a%
    

    @echo off
    echo do something
    call :timeloop
    echo do something else
    call :timeloop
    goto :eof
    :timeloop
    set a=%date%_%time%
    timeout /t 1 > nul
    echo %a%
    
        4
  •  1
  •   Julio    7 年前

    您可以将此作为替代方案:

    @echo off
    
    call :printdate
    REM here I wait 2 seconds to test different timestamp values
    timeout 2 1>NUL
    call :printdate
    
    pause
    exit /B 0
    
    :printdate
    echo The timestamp is: %DATE%-%TIME%
    goto :eof
    

    输出:

    The timestamp is: 17/08/2018-13:40:10,37
    The timestamp is: 17/08/2018-13:40:12,16
    

    @echo off
    
    call :printdate "The OLD timestamp is: "
    REM here I wait 2 seconds to test different timestamp values
    timeout 2 1>NUL
    call :printdate "The NEW timestamp is: "
    
    pause
    exit /B 0
    
    :printdate
    echo %~1 %DATE%-%TIME%
    goto :eof
    

    输出:

    The OLD timestamp is:  17/08/2018-13:54:46,24
    The NEW timestamp is:  17/08/2018-13:54:48,14
    
    推荐文章