4MAY
Batch programming can be a powerful thing. Basically, anything you can run at a command prompt can be run in a batch file. Coupled with task scheduler, process automation nirvana can be achieved.
However, one thing that is conspicuously is the presence of a date or time variable. For example, if you wanted to date or time encode a filename or create a log entry, you have no way to do that in native batch. But there is a way!
There is a DATE command is available though. With a simple bit of trickery, we can grab that info and store it in a variable, then use it however we want within our script.
The actual code is posted at the bottom of this article, but I want to give a basic flow/explanation of what is going on with it first. Because knowledge is power, that's why. And not everyone is a seasoned IT professional.
.echo off
echo *** Finding DateStamp YYYYMMDD
REM ***
REM *** Echo date to null. If the date command is not available, exit the script
REM ***
echo. | date | FIND "(mm" > NUL
If errorlevel 1,(call :Parsedate DD MM) Else,(call :Parsedate MM DD)
goto :ScriptDone
:Parsedate ----------------------------------------------------------
REM ***
REM *** The date is available. Parse the output of DATE /T
REM ***
For /F "tokens=1-4 delims=/.- " %%A in ('date /T') do if %%D!==! (set %1=%%A&set %2=%%B&set YYYY=%%C) else (set DOW=%%A&set %1=%%B&set %2=%%C&set YYYY=%%D)
(Set DateStamp=%YYYY%%MM%%DD%)
REM ***
REM *** Example usage of DateStamp variable
REM ***
echo *** Datestamp:%DateStamp%
REM ***
REM *** Sample usage of the variable
REM ***
REM *** first, create a directory with the datestamp pre-pended to the directory name
mkdir k:\backup\%DateStamp%-webroot
REM *** copy a file with the date in the filename
copy c:\myfile.txt k:\backup\%DateStamp%_myfile.txt
:ScriptDone
Posted On 2012-05-04 by dwirch
Keywords:
Tags: Windows Commandline Scripting Tutorial Windows
Views: 542
No comments on this post yet!
You must be logged in to post a comment.