Setting a windows batch file variable to the day of the week

batch-file, scripting, windows

Solution

`%DATE%` is not your friend. Because the `%DATE%` environment variable (and the `DATE` command) returns the current date using the Windows short date format that is fully and endlessly customizable. One user may configure the system to return 07/06/2012 while another might choose Fri060712. Using `%DATE%` is a complete nightmare for a BAT programmer.

There are two possible approaches to solve this problem:

You may be tempted to temporarily change the short date format, by changing the locale settings in the registry value `HKCU\Control Panel\International\sShortDate`, to your recognizable format. Then access `%DATE%` to get the date in the format you want; and finally restore the format back to the original user format. Something like this

reg copy "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp" /f >nul
reg add "HKCU\Control Panel\International" /v sShortDate /d "ddd" /f >nul
set DOW=%DATE%
reg copy "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f >nul

but this method has two problems:

it tampers with a global registry value for its local particular purpouses, so it may interfere with other processes or user tasks that at the very same time query the date in short date format, including itself if run simultaneously.

and it returns the three letter day of the week in the local language that may be different in different systems or different users.

use WMIC Win32_LocalTime, that returns the date in a convenient way to directly parse it with a `FOR` command.

FOR /F "skip=1" %%A IN ('WMIC Path Win32_LocalTime Get DayOfWeek' ) DO (
  set DOW=%%A
)

this is the method I recommend.

Problem

I have a windows batch file that runs daily. Wish to log data into a file and want to rotate it (i.e. having at most the last 7 days worth of data). Looked into the commands `DATE` and `DELIMS` - Cannot figure out a solution. Is there a simple solution to create a file name that contains the day of the week i.e. 0 for monday etc. Or do I have to resort to some better shell script.

Original source

Related problems