将 Windows 批处理文件变量设置为星期几 [英] Setting a windows batch file variable to the day of the week

查看:56
本文介绍了将 Windows 批处理文件变量设置为星期几的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个每天运行的 Windows 批处理文件.希望将数据记录到文件中并希望轮换它(即最多拥有过去 7 天的数据).

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).

查看命令 DATEDELIMS - 无法找到解决方案.

Looked into the commands DATE and DELIMS - Cannot figure out a solution.

是否有一个简单的解决方案来创建一个包含星期几的文件名,即 0 代表星期一等.

Is there a simple solution to create a file name that contains the day of the week i.e. 0 for monday etc.

或者我必须求助于一些更好的 shell 脚本.

Or do I have to resort to some better shell script.

推荐答案

%DATE% 不是你的朋友.因为 %DATE% 环境变量(和 DATE 命令)使用 Windows 短日期格式返回当前日期,该格式是完全可无限定制的.一个用户可以将系统配置为返回 07/06/2012,而另一个用户可能选择 Fri060712.使用 %DATE% 对 BAT 程序员来说简直就是一场噩梦.

%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:

  1. 您可能想临时更改短日期格式,方法是将注册表值 HKCUControl PanelInternationalsShortDate 中的区域设置更改为您可识别的格式.然后访问 %DATE% 以获取所需格式的日期;最后将格式恢复回原来的用户格式.像这样

  1. You may be tempted to temporarily change the short date format, by changing the locale settings in the registry value HKCUControl PanelInternationalsShortDate, 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 "HKCUControl PanelInternational" "HKCUControl PanelInternational-Temp" /f >nul
reg add "HKCUControl PanelInternational" /v sShortDate /d "ddd" /f >nul
set DOW=%DATE%
reg copy "HKCUControl PanelInternational-Temp" "HKCUControl PanelInternational" /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.

使用 WMIC Win32_LocalTime,它以一种方便的方式返回日期,以便使用 FOR 命令直接解析它.

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
)

这是我推荐的方法.

这篇关于将 Windows 批处理文件变量设置为星期几的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆