Sunday, December 13, 2009

Creating Directories in Batch Files

Creating new directories using batch files is a common task for system administrators and even home users. But it's not so simple to create a directory with the proper name sometimes. For example, let's consider that we want to create a directory named using the current date and current time. How will you create it through a batch script? Probably you will type something like this:
md %date%%time:~0,2%%time:~3,2%
Now let's execute this code... What a surprise! We get two different folders instead of a single one. Why? Windows includes space into the
folder's name, and thus 'md' command considers creating two directories. Two folders will be created when time is then 10 a.m., e.g. when it can be represented with a single digit.
To solve this problem, we decided to remove space between the date and time. Here is the proper code to create directory with such name:
set d=%date%_%time:~0,2%.%time:~3,2%
set dt=%d: =%
md %dt%
This code will always create a single folder any time you call it.

No comments:

Post a Comment

Translate