Tuesday, November 08, 2011

Create a date and time stamp in your batch files | Remote Administration For Windows

DOS scripts at their best.  DOS better be in Windows 8…

Here is an interesting one. I found a way to take the %date% environment variable, and turn it into a valid string for a filename – without any extra programs or scripts.

For the longest time I used a little utility I created to do this. The problem with that is the utility needs to be around if you want to send the batch file to someone.

What I didn’t know that was that you can use this character combination ‘:~’ to pull a substring out of an environment variable. That is when I realized you could use this to pull out parts of the current date (or time).

Here is how it works. Lets take the %date% variable and print it out

Create a date and time stamp in your batch files | Remote Administration For Windows

Here’s an example including time that backs up a projects directory to the C: drive under a Backup timestamped directory.

@echo off
set YYYYMMDD=%date:~-4,4%%date:~-10,2%%date:~-7,2%
set HHMMSS=%time:~-11,2%%time:~-8,2%%time:~-5,2%
echo %HHMMSS%


c:
md \Backup_%YYYYMMDD%%HHMMSS%

echo Backing Up files to \Backup_%YYYYMMDD%%HHMMSS%\

xcopy /s C:\Projects\*.* \Backup_%YYYYMMDD%%HHMMSS%\

echo Files backed up to \Backup_%YYYYMMDD%%HHMMSS%\

Goto Quit

:Quit

No comments: