Sudhir
Sudhir

Reputation: 21

Prefix file created datetime for multiple files with specific extension in a directory

I want to rename all the sql files in a directory by prefixing them with the date and time the file was created.

I am new to command prompt, came up with below code from what I read but it is not working.

for /f "delims=*" %%I in ('dir *.sql /b /s') do (    
set dt=%%~tI     
for /f "delims=/: " %%a in ('%dt%') do (set mydate=%%a)     
for /f "delims=/: " %%b in ('%dt%') do (set mytime=%%b)     
ren %%~nI.sql %mydate%%mytime%_%%~nI.sql)    

Upvotes: 2

Views: 315

Answers (2)

Arun
Arun

Reputation: 582

ren "%file" "%date:~0,2%.%date:~3,2%.%date:~6,4%-%time-somename.sql"

Upvotes: 0

Luke Z
Luke Z

Reputation: 2419

Something like this should work if the batch file is in the same directory as the sql files:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
for /f "tokens=*" %%f in ('dir /b *.sql') do (
  set createtime=%%~tf
  set createtime=!createtime:/=!
  set createtime=!createtime::=!
  rename "%%f" "!createtime! %%f"
)

The 2nd and 3rd set createtime lines are replacing / and : (respectively) with null because those are invalid characters for a filename. If you prefer you could replace them with something else instead (e.g. -) by inserting this value to the right of the = character.

Note that the %%~t modifier used here (and in your example) actually gets the modified time of the file, not the created time. This would only be noticeable if your sql files are modified after they're created.

Also, there is nothing here to prevent it from prefixing the same files with additional timestamps if the script is executed more than once, so keep that in mind.

Upvotes: 1

Related Questions