Windows – batch file to dump data from database and dynamically name the file name

batch-filewindows

I have a batch process that dumps data from my database (windows 2008 r2) and I'd like to dynamically name my file with the day of the week included.

is that possible to do with a simple .bat file?

if so how?

Best Answer

Sure:

Assumes you have your regional date setting as such:

  • Short: M/d/yyyy
  • Long: dddd, MMMM dd, yyyy

At the top of your batch file, you can set an environment variable called fname:

set fname=%date:~0,3%

Today (which is Wednesday) fname would be set to Wed. In your batch file, you would replace the static file name with %fname%

You can add static text to this dynamically changing name easily:

set fname=%date:~0,3%-backup.foo

fname would be set to: Wed-backup.foo

As I commented above, you can add more date related info:

set fname=%date:~0,3%-%date:~10,4%%date:~4,2%%date:~7,2%.foo

fname would be set to: Wed-20111019.foo

You can add a path by either prepending to your 'set fname' variable, or when you use the %fname% variable in the script: set fname=c:\backup\%date:~0,3%-%date:~10,4%%date:~4,2%%date:~7,2%.foo, or at the point of use: "c:\backup\%fname%"

Remember to use Quotes if there are spaces in the path or filename.