在批处理脚本中使用%date%

时间:2018-06-04 21:46:32

标签: date batch-file

我想要一些像这样的代码:

if %date% equ "Mon" echo do this do that

但是在遇到此代码后cmd窗口关闭,即使我放了

pause

之后。 我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

您可能想要使用:

IF /I "%DATE:~,3%"=="Mon" (Echo Do this
    Echo Do that)

或者可能:

IF NOT "%DATE:Mon=%"=="%DATE%" (Echo Do this
    Echo Do that)

然而,除了特定的当前用户环境之外,其他任何一种都不是安全或强大的方法。

这就是我使用WMIC的批处理文件将一周中的某一天变为变量的方式:

For /F %%A In ('WMIC Path Win32_LocalTime Get DayOfWeek') Do For %%B In (
    Monday.1 Tuesday.2 Wednesday.3 Thursday.4 Friday.5 Saturday.6 Sunday.0
) Do If "%%~xB"==".%%A" Set "WDName=%%~nB"

2可以选择调整,以便在必要时使用Sunday.0 Monday.1等,或Lunes.1 Martes.2等等,具体取决于您的语言。

然后你可以使用:

If "%WDName%"=="Monday" (Echo Do this
    Echo Do that)

虽然PowerShell中的(Get-Date).DayOfWeek看起来更简单。

答案 1 :(得分:0)

这是一个完整的cmd文件,可以满足您的需求。重要的一点都在getDow函数中,希望它的评论能够很好地理解。首先,测试工具:

@echo off
rem Test harness bit - just get current date and compare with getDow.

date /t
call :getDow num long short
echo Day of week is %num%, %long%, %short%
goto :eof

该功能本身是:

rem Usage: call :getDow <num> <long> <short>
rem        <num> will receive the numeric form (0-6).
rem        <long> will receive the long form (e.g., Monday).
rem        <short> will receive the short form (e.g., Mon).

:getDow
    rem Create local scope to prevent information leakage.

    setlocal enableextensions enabledelayedexpansion

    rem Create array for translation.

    set idx=0
    for %%a in (Sunday Monday Tuesday Wednesday Thursday Friday Saturday) do (
        set dow[!idx!]=%%a
        set /a "idx += 1"
    )

    rem Get the numeric day of week, mmi command will
    rem output 'DayOfWeek=N' and we just extract N.

    for /f "tokens=2 delims==" %%a in ('WMIC Path Win32_LocalTime Get DayOfWeek /value ^| findstr "DayOfWeek="') do (
        set localNum=%%a
    )
    set localStr=!dow[%localNum%]!

    rem Properly end scope but let selected information leak.

    endlocal&&set %1=%localNum%&&set %2=%localStr%&&set %3=%localStr:~0,3%
    goto :eof

该脚本的示例运行提供:

Tue Jun 05
Day of week is 2, Tuesday, Tue