blog:130625_realiable_way_to_get_date_in_batch_scripting

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
Last revisionBoth sides next revision
blog:130625_realiable_way_to_get_date_in_batch_scripting [2013/07/03 12:26] – external edit 127.0.0.1blog:130625_realiable_way_to_get_date_in_batch_scripting [2021/04/04 00:16] Ignas
Line 1: Line 1:
 +====== 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 <wrap hi>file_%date%.bak</wrap> 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 WMI((Windows Management Instrument)) 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: 
 +<WRAP center round info 55%>YearMonthDayHourMinuteSecond.Microsecond+Timezone\\ **20130625094846.381000+180**</WRAP>
 +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:
 +<code dos>
 +@ECHO OFF
 +for /f %%a in ('wmic os get LocalDateTime ^| findstr ^[0-9]') do (set ts=%%a)
 +ECHO %ts:~0,8%-%ts:~8,4%
 +</code>
 +
 +This way I get **20130625-0948**\\
 +
 +So just script your filename as following and you are ready to go
 +<code dos>SET filename = %ts:~0,8%.bak</code>
 +
 +{{tag> cmd command line console naming date VMI}}
 +
 +~~DISCUSSION~~
  • blog/130625_realiable_way_to_get_date_in_batch_scripting.txt
  • Last modified: 2021/11/19 18:20
  • by Ignas