Rename files to add date modified to filename with Windows CMD or simple .TXT

Solution 1:

In Powershell you can do this with a One-Liner:

Get-ChildItem |Foreach-Object { Rename-Item $_ -NewName ("{0}-{1}{2}" -f $_.BaseName,$_.LastWriteTime.ToString('yyyyMMdd'),$_.Extension)  }

Explanation:

  • Get-ChildItem: Gets all items in the directory. You could add -Recurse to get files from sub directories too
  • Foreach-Object: Run the following code block with each file
  • $_: The current iterated file as an object
  • $_.BaseName: The filename without extension
  • $_.LastWriteTime: The last write time as a DateTime object
    The method .ToString() allows you to format as you need it
  • $_.Extension: The extension of the file

Solution 2:

Here is the code you need to use to iterate the text files, obtain the modified date of each file, copy each file using the modified date as part of the file name, and delete the original files. You were very close, but you were missing a few things.

To get the modify date of a file we can use set "MDate=%%~tF".

To parse the date that is provided by set "MDate=%%~tF" you will need to specify which parts of the value stored by %MDate% you want to use in the output. You can use the command set "ParsedDate=!MDate:~6,4!!MDate:~0,2!!MDate:~3,2!" to convert the output of set "MDate=%%~tF" from MM/DD/YYYY hh:mm to YYYYMMDD.

After that we can copy the files to new files using the value of %ParsedDate% in the filename.

You should see two copies of the files. If you want to delete the original files we just need to run the command for %%F in ("C:\test\*.txt") do ( del %%F ). That will leave you with the renamed text files. To convert the .txt.new to .txt use the command ren "C:\test\*.new" *..

Because we are in a for loop we need to change how we address varables (which based on what you have written so far you already know). We change % to ! for variable names inside a loop. So if you have the variable name example you would reference the variable using !example! inside the loop instead of %example%.

For variables inside the loop to work we also need to add the command setlocal enabledelayedexpansion before the loop.

That should cover everything. Please feel free to upvote or mark the answer as correct if this solves your problem.

The full batch file is provided below.

setlocal enabledelayedexpansion

for %%F in ("C:\test\*.txt") do ( 
    set "MDate=%%~tF"
    set "ParsedDate=!MDate:~6,4!!MDate:~0,2!!MDate:~3,2!"
    REM To add time
    set "ParsedDate=!MDate:~6,4!!MDate:~3,2!!MDate:~0,2!!MDate:~11,2!!MDate:~14,2!"
    copy %%F %%~dpnF_!ParsedDate!%%~xF.new )

for %%F in ("C:\test\*.txt") do ( 
    del %%F )

ren "C:\test\*.new" *.

exit