This is something that I should have posted a long time ago. Sadly though, with things like PowerShell out now, old school batch files are quickly becoming extinct, even for hardened batchers like myself. However I still find myself using batch files of some sort from time to time, and often times I need to utilize the date in some form or another… either to make a decision, to store and pass in an environment variable, or to use to format a file name. I’m sure there are plenty of admins out there that do the same, hence this post.
Unfortunately, something I see constantly are all kinds of crazy solutions for getting the system date and time in a batch file. Some involve 3rd party utilities, while others involve filtering and dumping date/time data to sub-batch files, etc. However, the best, cleanest way to get the system date and time is to use the built-in data parsing functions that the DOS emulator has had since at least Windows 2000.
The syntax looks like this %date:~S,L% where S is starting character position of date substring and L is the substring length. This syntax can be dumped into an environment variable, or used directly in file names. For example, you could use “%date:~10,4%-%date:~4,2%-%date:~7,2%_backup.zip” in a daily batch file to generate backup targets with “yyyy-mm-dd_backup.zip” formatted file names.
Simple, right?
Another fun trick is getting the path of the batch file currently running; echo %~dp0
Tags: software












