3

I rename a bunch of files and prepend the file's creation time including seconds into the file name while keeping the original at the end. Preferably in a 24 hour format but am/pm is okay too.

Ideal example: Video001.mp4 becomes 20160421-153242-Video001.mp4, Video002.mp4 becomes 20160421-153248-Video002.mp4. Format can vary a bit.

Here's the code I have written which is CLOSE, but doesn't include seconds:

@echo off

FOR %%V IN (%1) DO (
FOR /F "tokens=1-6 delims=/: " %%J IN ("%%~tV") DO (

IF EXIST %%L%%J%%K_%%O%%M%%N-%%~nV%%~xV (ECHO Cannot rename %%V)

ELSE (Rename "%%V" %%L%%J%%K_%%O%%M%%N-%%~nV%%~xV)

I can't figure out how to get the SECONDS part of the CREATION time for the file. I've searched around but haven't really found the right answer :(.

Application is allowing an easy sort of video files by creation date (between multiple camera sources).

Mofi
  • 46,139
  • 17
  • 80
  • 143
N. Johnson
  • 101
  • 1
  • 7
  • 1
    You should search it firstly, which can be easily found [link 1](http://stackoverflow.com/questions/864718/how-to-append-a-date-in-batch-files) [link 2](http://stackoverflow.com/questions/1192476/format-date-and-time-in-a-windows-batch-script) [link 3](http://stackoverflow.com/questions/5594121/batch-script-date-into-variable) [link 4](http://ss64.com/nt/syntax-getdate.html) – enjoying Apr 21 '16 at 06:55
  • @enjoying None of those 4 links help here as they are all about renaming a file with adding current local time. But asked was how add `file's creation time including seconds` to file name which requires other methods, see the code in my answer. – Mofi Apr 21 '16 at 15:24

3 Answers3

2

You could use the following commented batch code:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
if "%~1" == "" goto :EOF
for /F delims^=?*^ eol^= %%I in ("%~1") do if "%~1" == "%%I" goto NoPattern
for %%I in (%1) do set "FilePath=%%~dpI" & goto ProcessFiles
echo ERROR: There is no file matched by: "%~1"
goto :EOF
:NoPattern
rem Get full name of directory or file.
for %%I in (%1) do set "FilePath=%%~fI"
if not "%FilePath:~-1%" == "\" set "FilePath=%FilePath%\"
rem References the passed argument string an existing directory?
if exist "%FilePath%" goto ProcessFiles
rem References the passed argument string an existing file?
if exist %1 set "FilePath=%~dp1" & goto ProcessFiles
echo ERROR: Could not find: "%~1"
goto :EOF

:ProcessFiles
rem Escape each backslash in file path with one more backslash.
set "EscapedFilePath=%FilePath:\=\\%"

for /F "eol=| delims=" %%I in ('dir %1 /A-D-H /B 2^>nul') do (

    rem Get name of file without path.
    set "FileName=%%I"
    setlocal EnableDelayedExpansion
    set "EscapedName=!FileName:'=\'!"
    set "FileDateTime="

    rem Get creation date and time of file in format YYYYMMDDHHMMSS.
    for /F "usebackq tokens=2 delims==." %%J in (`%SystemRoot%\System32\wbem\wmic.exe DATAFILE where "name='!EscapedFilePath!!EscapedName!'" GET CreationDate /VALUE 2^>nul`) do set "FileDateTime=%%J"

    if defined FileDateTime (
        rem The first eight characters are the file creation date.
        set "FileDate=!FileDateTime:~0,8!"
        rem The next six characters are the file creation time.
        set "FileTime=!FileDateTime:~8,6!"

        rem Get the first sixteen characters of the current file name.
        set "FileNameStart=!FileName:~0,16!"

        rem Rename the current file only if its name does not already start with the
        rem creation date and time to avoid renaming the same files again and again.
        if not "!FileNameStart!" == "!FileDate!-!FileTime!-" (
            if not exist "!FilePath!!FileDate!-!FileTime!-!FileName!" (
                ren "%FilePath%!FileName!" "!FileDate!-!FileTime!-!FileName!" 2>nul
                if errorlevel 1 echo ERROR: Failed to rename file: "%FilePath%!FileName!"
            ) else (
                echo ERROR: Cannot rename file: "%FilePath%!FileName!"
                echo        There is already a file with name: "!FileDate!-!FileTime!-!FileName!"
            )
        )
    ) else (
        echo ERROR: Failed to get file time for: "%FilePath%!FileName!"
        echo        It is necessary to change manually the file name.
    )
    endlocal
)
endlocal

NOTE: This batch file cannot rename files containing one or more commas in file name!

%%~tV expands to last modification file time in a region and language dependent format without second. But wanted is the creation file time with the second.

WMIC - the Windows Management Instrumentation Command-line utility - can be used to get creation file time with second in a region and language independent date/time format. The disadvantage of usage of WMIC is the speed. This command is very slow. For more details about WMIC usage for file times read my answer on Find out if file is older than 4 hours in batch file.

Use LastModified instead of CreationDate if you want last modification file time instead of creation file time.

What is the difference between creation and last modified date?

The last modified date is the date on which the content of the file was modified last time.

The creation date is the date on which the file was first time created in the directory it is currently stored.

For example if a file was created new yesterday, it has same creation and last modified date because the file was created in the directory and the content was last modified at the same time. If the file is copied today to a different directory, the last modified date is still the same date (yesterday), but the creation date of the copy is today.

Most people are interested only in last modified date and not in file creation date because important is when the file content was modified the last time and not when the file was created in the current directory.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • call /? ... for an explanation of %1 and %~1
  • dir /?
  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • if /?
  • rem /?
  • ren /?
  • set /?
  • setlocal /?
  • wmic /?
  • wmic datafile /?
  • wmic datafile get /?
Mofi
  • 46,139
  • 17
  • 80
  • 143
1

You cannot get the seconds from pure batch syntax. For that, you need to use another tool. The following PowerShell script does what you are asking:

MyRename.ps1

dir $args[0] | foreach {
  $newname = "$($_.CreationTime.toString('yyyyMMdd-HHmmss'))-$($_.Name)"
  if (test-path $newname) {
    "Cannot rename $_"
  } else {
    ren $_ $newname -WhatIf
  }
}

Note: This code only shows what would be renamed. To actually perform the rename, remove the -WhatIf parameter from the ren command

If you want the Modified time instead of the Creation time, change $_.CreationTime in the script to $_.LastWriteTime .

To call this PowerShell script from a batch file, run powershell.exe

powershell -f .\MyRename.ps1 *.mp4

If you get an error about running scripts is disabled, add -ExecutionPolicy bypass to the command line.

powershell -ExecutionPolicy bypass -f .\MyRename.ps1 *.mp4
Ryan Bemrose
  • 9,018
  • 1
  • 41
  • 54
0

based on the answer of @Mofi to the OP, and this, here is my version allowing to rename multiples files with drag and drop :

@echo off
if "%~1" == "" goto :eof
SETLOCAL EnableDelayedExpansion

REM outer loop
for %%V in (%*) do (
    set "FileName=%%~fV"
    set "FileName=!FileName:\=\\!"
    set "FileName=!FileName:'=\'!"

    call :sub "!FileName!"

    set "FileDate=!FileDateTime:~0,8!"
    set "FileTime=!FileDateTime:~8,6!"

    if exist "!FileDate!_!FileTime!-%%~nV%%~xV" (
        echo Cannot rename file: %%~fV
    ) else (
        ren "%%~fV" "!FileDate!-!FileTime!-%%~nV%%~xV"
    )
)
REM ENDLOCAL
goto :eof

REM inner loop
:sub
for /F "usebackq skip=1 tokens=1 delims=." %%T in (`%SystemRoot%\System32\wbem\wmic.exe DATAFILE where "name='%~1'" get CreationDate`) do set "FileDateTime=%%T" & goto :next
:next
goto :eof

EDIT: little changes to so it works with white spaces in path or file name ;)

EDIT2: little changes to replace single quotes ' to \' to escape them in path or filename

hymced
  • 570
  • 5
  • 19