Batch Script to add date to a filename

Is it possible, and how would i go about it, creating a script that lives in a folder and whenever a file is added to the folder add the date (in the format yyyyMMdd) to the end of it as well as an incrementing number ie _1 then _2 to the end of files created on the same day?
AWSHelpdeskAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Steve KnightIT ConsultancyCommented:
OK, assuming you will schedule this to run then you want something like this.  Save it as renamefiles.cmd or something similar.

Remove the word "echo" from before the rename command to enable it and you will have to change the entries for the folder and the file type if needed.

Steve

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

REM Make temporary VBScript file to get date in correct format
ECHO wscript.echo year(date) ^& right(100+month(date),2) ^& right(100+day(date),2) >"%temp%\dateparts.vbs"

FOR /F "TOKENS=1" %%a IN ('cscript //nologo "%temp%\dateparts.vbs"') DO SET yyyymmdd=%%a
ECHO The date in YYYYMMDD format is %yyyymmdd%

REM Now look for files in the startdir which do not have an _ in them and rename (we may need to look at more appropriate filter to find them if they may have _ in them etc.

SET startdir=c:\myfolder
SET filetype=*.*
SET lastnumber=0

REM Get last number use if there are existing for today
FOR /F "TOKENS=2 DELIMS=_" %%a in ('DIR /B /A-D "%startdir%\*%yyyymmdd%_%filetype%"') DO IF %%a GTR !lastnumber! (SET lastnumber=%%a)

REM Make next number for todays files
SET /A nextnumber=%lastnumber% + 1

FOR /F "TOKENS=*" %%a in ('DIR /B /A-D "%startdir%\%filetype%"^|FIND /V "_"') DO (
  ECHO Have found a file without an _ in it -- %%a. Rename to %%~na %yyyymmdd%_!nextnumber!%%~xa
  echo RENAME "%%a" "%%~na %yyyymmdd%_!nextnumber!%%~xa"
  SET /A nextnumber=!nextnumber! + 1
)


The way of getting the date I take from my article here which explains more:

http://www.experts-exchange.com/articles/OS/Microsoft_Operating_Systems/MS_DOS/Using-dates-in-batch-files-scripts.html
0
Steve KnightIT ConsultancyCommented:
Have uploaded file as sometimes you get extra spaces at end of lines when copy / pasting otherwise.
renameincdate.cmd
0
Steve KnightIT ConsultancyCommented:
Actually two minor changes as my test data didn't have extensions on the files (oops).  Add "." in the DELIMS entry and to be sure add a CD command into the right dir.  Re-attached:
renameincdate.cmd
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Why Diversity in Tech Matters

Kesha Williams, certified professional and software developer, explores the imbalance of diversity in the world of technology -- especially when it comes to hiring women. She showcases ways she's making a difference through the Colors of STEM program.

AWSHelpdeskAuthor Commented:
Thanks Dragon-IT:

I get the following errors:

'\\c:\files\'
CMD.EXE was started with the above path as the current directory.
UNC paths are not supported.  Defaulting to Windows directory.
The date in YYYYMMDD format is 20100427
The syntax of the command is incorrect.
File Not Found
Have found a file without an _ in it -- renameincdate.cmd. Rename to renameincda
te 20100427_1.cmd
The system cannot find the file specified.
0
AWSHelpdeskAuthor Commented:
I mean:

'\\server\files'
CMD.EXE was started with the above path as the current directory.
UNC paths are not supported.  Defaulting to Windows directory.
The date in YYYYMMDD format is 20100427
The syntax of the command is incorrect.
File Not Found

I ahve changed CD to pushd to deal with the UNC path but i still seem to get this error. also not sure what the syntax error is from, i have attached the full code
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

REM Make temporary VBScript file to get date in correct format
ECHO wscript.echo year(date) ^& right(100+month(date),2) ^& right(100+day(date),2) >"%temp%\dateparts.vbs"

FOR /F "TOKENS=1" %%a IN ('cscript //nologo "%temp%\dateparts.vbs"') DO SET yyyymmdd=%%a
ECHO The date in YYYYMMDD format is %yyyymmdd%

REM Now look for files in the startdir which do not have an _ in them and rename (we may need to look at more appropriate filter to find them if they may have _ in them etc.

SET startdir=\\server\files
SET filetype=*.csv
SET lastnumber=0

pushd /D "%startdir%"

REM Get last number use if there are existing for today
FOR /F "TOKENS=2 DELIMS=_." %%a in ('DIR /B /A-D "%startdir%\*%yyyymmdd%_%filetype%"') DO IF %%a GTR !lastnumber! (SET lastnumber=%%a)

REM Make next number for todays files
SET /A nextnumber=%lastnumber% + 1

FOR /F "TOKENS=*" %%a in ('DIR /B /A-D "%startdir%\%filetype%"^|FIND /V "_"') DO (
  ECHO Have found a file without an _ in it -- %%a. Rename to %%~na %yyyymmdd%_!nextnumber!%%~xa
  RENAME "%%a" "%%~na %yyyymmdd%_!nextnumber!%%~xa"
  SET /A nextnumber=!nextnumber! + 1
)
pause

Open in new window

0
Steve KnightIT ConsultancyCommented:
could you run it please with the @echo off REM'd out at the top to see where the File not found and Syntax of command error are?
0
Steve KnightIT ConsultancyCommented:
V.Late now, will look back tomorrow.

Steve
0
Bill PrewIT / Software Engineering ConsultantCommented:
Not trying to horn in on points, but suspect Steve is offline for the evening.

First problem I see is the /D switch on the PUSHD command, that's an invalid switch for that command,remove it,I think that is the syntax error.

Second, the file not found error is actually okay if there are no files that have already been renamed.  The script works as needed, but we can suppress that error as follows:

FOR /F "TOKENS=2 DELIMS=_." %%a in ('DIR /B /A-D "%startdir%\*%yyyymmdd%_%filetype%" 2^>NUL') DO IF %%a GTR !lastnumber! (SET lastnumber=%%a)

Hope this helps.

~bp
0
AWSHelpdeskAuthor Commented:
Thanks billprew, i have fixed the issues now and it is now adding the date and _1 on the end - BUT i need it to add _date_1, where do i add this extra _ at between the existing filename and the date?
0
Bill PrewIT / Software Engineering ConsultantCommented:
You can just adjust the rename command as follows (and ECHO to match):

ECHO Have found a file without an _ in it -- %%a. Rename to %%~na_%yyyymmdd%_!nextnumber!%%~xa
RENAME "%%a" "%%~na_%yyyymmdd%_!nextnumber!%%~xa"

~bp
0
AWSHelpdeskAuthor Commented:
billprew! AWESOME, thanks so much to both of you

One final thing (as i am new to the whole batch file thing) is there a way to trigger this to run whenever a new file is added to the folder?
0
Bill PrewIT / Software Engineering ConsultantCommented:
There isn't really any easy way to immediately run this any time a new file is added to the folder using basic built in Windows capabilities.

One approach, which is what Steve assumed here, is to set up the BAT file to run in a "polling mode", basically running the batch file every so many minutes, and letting it check for an new files to process and handle them.  This can be done with the Task Scheduler and you could have a relatively short interval without problems, say every 5 minutes.

If you want true "triggering" as soon as a file is added then you will likely be looking at purchasing a third party addon utility that will monitor a directory constantly, and as soon as a file is added can then run the batch file.  One example can be seen at the link below:

http://www.watchdirectory.net/

~bp
0
AWSHelpdeskAuthor Commented:
PERFECT, i have setup a Schedule
0
Bill PrewIT / Software Engineering ConsultantCommented:
Thanks, glad that was helpful. Steve did most of the heavy lifting with his foundation, and I'm sure would have supplied similar advice as I did if he was actually awake now.

~bp
0
Steve KnightIT ConsultancyCommented:
thanks bill for that... was 1am after long day... and is now 6am after short night of broken sleep.

Thanks for finishing off and debugging his changes as brain couldnt take any more thinking!

Steve
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Windows Batch

From novice to tech pro — start learning today.