blog:130625_realiable_way_to_get_date_in_batch_scripting

Reliable way to get date in batch scripting

It's been long time since my last post, but I'm here, and watching :-)

Lately, I've got assignment to create MySQL backup script. It must be automatically scheduled by MS Windows Task Scheduler. As it is automatic, script should create new backup name each time. What is the best way to name backups? Probably to include date of backup.
And here my problems begins. If you grab date file_%date%.bak you may end up in various ways:

  • File can be created and named as you've expected;
  • Back up file does not appear (because of illegal characters used as date separator);
  • Backup file named somehow strangely.

I've tried all various ways to create file names as I wanted to by splitting date into Year, Mont and Day. But when it comes to locale- date can be in imperial style: YYYY/DD/MM
I want universal script to work on all locales or formats, so tried to catch date separator to guess format. This kind of tinkering complicated my script till unusable… And suddenly I step over WMI1) once again. This instrument is life saver. For real!! I have found Win32_OperatingSystem class in root\CIMV2 namespace. And you know what? It has exactly what I need. I just needed to query LocalDateTime property to get Date and time. This property hold my valuables in this format:

YearMonthDayHourMinuteSecond.Microsecond+Timezone
20130625094846.381000+180

This format is independent from locale or whatever else factors, it's allways the same.
Now I see my road bright and clear- I must use WMI to get my date and split it into Year, Mont and Day. This could be done quite simply in batch scripting file:

@ECHO OFF
for /f %%a in ('wmic os get LocalDateTime ^| findstr ^[0-9]') do (set ts=%%a)
ECHO %ts:~0,8%-%ts:~8,4%

This way I get 20130625-0948

So just script your filename as following and you are ready to go

SET filename = %ts:~0,8%.bak

1)
Windows Management Instrument
asdf, 2017/07/26 21:16
thank you brother for information
Enter your comment. Wiki syntax is allowed:
If you can't read the letters on the image, download this .wav file to get them read to you.
 
  • blog/130625_realiable_way_to_get_date_in_batch_scripting.txt
  • Last modified: 2021/11/19 18:20
  • by Ignas