Search code examples
batch-filebatch-rename

Rename file to creation time (batch file only)


Not sure this is possible with only a batch file.

I have a file named BaseFile.7z location is E:\Backup\C Drive Zip\BaseFile.7z

Is it possible to create a batch command that renames the file with its creation date? For example BaseFile - 02-19-2015.7z

I currently have a command that renames the file with the current date which I pasted below for reference, but thats not exactly what I'm looking for. I need creation date.

RENAME "E:\Backup\C Drive Zip\Jaipur.txt" "BaseFile - %date:/=-%.txt"

Solution

  • @ECHO OFF
    SETLOCAL
    SET "filename=U:\sourcedir\zzz.zzz"
    IF NOT EXIST "%filename%" ECHO "%filename%" NOT found&GOTO :eof
    SET "datepart="
    FOR /f "tokens=1-3delims=/-:" %%a IN ('dir /tc "%filename%"') DO IF "%%c" neq "" SET "datepart=%%a-%%b-%%c"
    FOR /f %%a IN ("%filename%") DO FOR /f %%d IN ("%datepart%") DO ECHO(REN "%%a" - "%%~na %%d%%~xa"
    GOTO :EOF
    

    The required REN command is merely ECHOed for testing purposes. After you've verified that the command is correct, change ECHO(REN to REN to actually rename the file.

    Note that there is general sloppiness in the use of date-references. There are three dates on each file - actual create date (use /tc), last access (/ta) and last-written (/tw).

    The process locates the file, then reads a dir listing with the appropriate date selected. The only or last line in the listing that will contain a third non-empty token is the date/time of the file in question, so datepart will acquire yyyy-mm-dd hh

    the for/f %%a then applies the full filename to %%a ready for partitionig into its components and the for/f %%d assigns the first token from datepart (ie up to the space) into %%d.

    Bang the components together, and the resut is reported...