Different result from command line prog when run by Task Scheduler

1

I call the following program from within another command line prog...

:: NT_getdate.cmd    return yumd-date in var='ymd'
@echo on
setlocal
for /F "tokens=2,3,4 delims=/ " %%g in ('echo.^|date /t') do (
    set dd=%%g
    set mm=%%h
    set yy=%%i
)
endlocal& set ymd=%yy%%mm%%dd%

When I run the progam from within command line ymd is returned as "20160501" which is what I want.

When I run the top program from Task Scheduler the result I get is "1605"

Any ideas?

SteveHMTM

Posted 2016-05-01T06:26:12.630

Reputation: 11

my guess is that the user running the command via task scheduler has a different environment than your desktop user does. have you tried scheduling the task under your own user? – Frank Thomas – 2016-05-01T06:44:55.313

have you tried just running date /t and then the pause command and compare the formats between batch file within cmd, and task scheduler – barlop – 2016-05-01T06:46:01.620

Answers

0

I would like to have the date formatted like 20160501

When I run the progam from within command line ymd is returned as "20160501" which is what I want.

When I run the top program from Task Scheduler the result I get is "1605"

Using %date% to provide a solution is dependent on the OS Locale, Regional, and Language settings. This explains why you are getting different outputs.

Using wmic, on the other hand, works independently of OS Locale, Language or the user's chosen date format (Control Panel/Regional).

The following batch file uses wmic to retrieve the date and (local) time in the OP's specified format, so doesn't suffer the disadvantage of a solution using %date%.

GetDate.cmd:

@echo off
setlocal
rem use findstr to strip blank lines from wmic output
for /f "usebackq skip=1 tokens=1-3" %%g in (`wmic Path Win32_LocalTime Get Day^,Month^,Year ^| findstr /r /v "^$"`) do (
  set _day=00%%g
  set _month=00%%h
  set _year=%%i
  )
  rem pad with leading zeros
  set _month=%_month:~-2%
  set _day=%_day:~-2%
  set _date=%_year%%_month%%_day%
  echo %_date%
endlocal

Notes:

  • The above batch file is a modified version of the example in getdate.
  • It is easily tweaked to meet your exact needs.
  • If you decide you also need the time (hours, minutes and seconds) then see my answer Print datetime in Windows cmd

Output:

F:\test>date /t
01/05/2016

F:\test>GetDate
20160501

F:\test>

Further Reading

  • An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
  • for /f - Loop command against the results of another command.
  • getdate - Display the date and time independent of OS Locale, Language or the users chosen date format (Control Panel/Regional).
  • variables - Extract part of a variable (substring).
  • wmic - Windows Management Instrumentation Command.

DavidPostill

Posted 2016-05-01T06:26:12.630

Reputation: 118 938