批处理文件运行cmd1,如果时间晚上10点到4点,则运行cmd2

jus*_*hil 4 batch-file

我有一个批处理文件,在该批处理文件中,我需要根据服务器的时间运行两个命令之一.

如果时间在22:00:00和03:30:00之间 - xcopy/Y a\1.txt c\1.txt

如果时间在此范围之前或之后 - - xcopy/Y b\1.txt c\1.txt

这将使用xcopy根据时间来回切换文件.

我知道这很容易,但我的大脑不会起作用

编辑:

去了22:00和4:00 ...这是我想出来的,但它似乎不是最好的方式......

set current_time =%time:~0.5%

if"%current_time%"lss"22:00"goto daycycle

if"%current_time%"gtr"4:00"goto daycycle

echo在晚上10点到凌晨4点之间这样做

转到继续

:daycycle

echo在晚上10点之前和凌晨4点之后这样做

:继续

MC *_* ND 6

@echo off
    setlocal enableextensions disabledelayedexpansion

    set "now=%time: =0%"

    set "task=day"
    if "%now%" lss "03:30:00,00" ( set "task=night" ) 
    if "%now%" geq "22:00:00,00" ( set "task=night" )

    call :task_%task%

    endlocal
    exit /b

:task_day
    :: do daily task
    goto :eof

:task_night
    :: do nightly task
    goto :eof
Run Code Online (Sandbox Code Playgroud)

编辑 - 以前的代码应该在原始问题的条件下工作.但是在不同的时间配置中会失败.这应该解决通常的问题

@echo off
    setlocal enableextensions disabledelayedexpansion

    call :getTime now

    set "task=day"
    if "%now%" lss "03:30:00,00" ( set "task=night" ) 
    if "%now%" geq "22:00:00,00" ( set "task=night" )

    call :task_%task%

    echo %now%

    endlocal
    exit /b

:task_day
    :: do daily task
    goto :eof

:task_night
    :: do nightly task
    goto :eof

:: getTime
::    This routine returns the current (or passed as argument) time
::    in the form hh:mm:ss,cc in 24h format, with two digits in each
::    of the segments, 0 prefixed where needed.
:getTime returnVar [time]
    setlocal enableextensions disabledelayedexpansion

    :: Retrieve parameters if present. Else take current time
    if "%~2"=="" ( set "t=%time%" ) else ( set "t=%~2" )

    :: Test if time contains "correct" (usual) data. Else try something else
    echo(%t%|findstr /i /r /x /c:"[0-9:,.apm -]*" >nul || ( 
        set "t="
        for /f "tokens=2" %%a in ('2^>nul robocopy "|" . /njh') do (
            if not defined t set "t=%%a,00"
        )
        rem If we do not have a valid time string, leave
        if not defined t exit /b
    )

    :: Check if 24h time adjust is needed
    if not "%t:pm=%"=="%t%" (set "p=12" ) else (set "p=0")

    :: Separate the elements of the time string
    for /f "tokens=1-5 delims=:.,-PpAaMm " %%a in ("%t%") do (
        set "h=%%a" & set "m=00%%b" & set "s=00%%c" & set "c=00%%d" 
    )

    :: Adjust the hour part of the time string
    set /a "h=100%h%+%p%"

    :: Clean up and return the new time string
    endlocal & if not "%~1"=="" set "%~1=%h:~-2%:%m:~-2%:%s:~-2%,%c:~-2%" & exit /b
Run Code Online (Sandbox Code Playgroud)