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

后端 未结 17 1993
南方客
南方客 2020-11-27 20:14

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

17条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 21:01

    Locale-dependent version: In some environments, the following will extract the day name from the date:

    set dayname=%date:~0,3%
    

    It assumes that the day name is the first part of %date%. Depending on the machine settings, though, the substring part (~0,3) would need to change.

    A statement such as this would dump to a file with a three character day name:

    set logfile=%date:~0,3%.log
    echo some stuff > %logfile%
    

    Locale-independent version: If you need it less dependent on the current machine's day format, another way of doing it would be to write a tiny application that prints the day of the week. Then use the output of that program from the batch file. For example, the following C application prints dayN where N=0..6.

    #include 
    #include 
    
    int main( int argc, char* argv[] )
    {
       time_t curtime;
       struct tm * tmval;
    
       time( &curtime );
       tmval = localtime( &curtime );
       // print dayN.  Or use a switch statement and print
       // the actual day name if you want
       printf( "day%d", tmval->tm_wday );
    }
    

    If the above were compiled and linked as myday.exe, then you could use it from a batch file like this:

    for /f %%d in ('myday.exe') do set logfile=%%d.log
    echo some stuff > %logfile%
    

提交回复
热议问题