Search code examples
windowsbatch-filecmdscheduled-taskswindows-server-2012

How can I tell if a Batch variable is text or a number?


This is a really simple thing that I'm having a horrible time figuring out.

I have a script. It breaks the date down into separate vars, like this:

for /f "tokens=1,2,3,4 delims=/ " %%a in ( 'DATE /T' ) do set DD=%%a&set MM=%%b&set YYYY=%%c
for /f "tokens=1,2,3,4 delims=:." %%e in ("%time%") do set HH=%%e&set MI=%%f&set SS=%%g

This is great in cmd! Until I make the script a scheduled task. When it's a scheduled task, the first token in DATE /T is the Day Name (as in Mon, Tue, Wed, etc.) The problem is that I need it to be the Date, and not the day.

To me, this should be a simple if statement to check if %%A is a number, but I cannot figure out how to check this. I've trawled through old blogs and questions here, but I've come up empty. Can anyone help?


Solution

  • you could try to set a variable as a number:

    set /a x=TUE
    id "%x%"="0" echo this is not a number
    

    But I recommend using a language independent solution:

    for /f %%i in ('wmic os get localdatetime^|find "."') do set x=%%i
    set YYYY=%x:~0,4%
    set MM=%x:~4,2%
    set DD=%x:~6,2%
    set HH=%x:~8,2%
    set MI=%x:~10,2%
    set SS=%x:~12,2%
    

    or, if you don't mind using other variable names and a missing leading 0 (like 8 for August instead of 08) :

    for /f %%i in ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /value ^|find "="') do set %%i
    

    and get

    Day=22
    Hour=17
    Minute=19
    Month=8
    Second=12
    Year=2014