CMD/BAT get date modified of all filenames and append to their filename

Related searches

I am having trouble with this script. I'll explain below the codeblock.

@Echo off
pushd "\\server\folder"
SETLOCAL EnableDelayedExpansion

@FOR /F "TOKENS=2" %%A IN ('WHERE /T "testfiles*.*"') DO @(
set fdate123=%%A
echo !fdate123:~5,9!0!fdate123:~0,1!!fdate123:~2,2!
call StringLen !fdate123!


Setlocal EnableDelayedExpansion
:: strLen String [RtnVar]
::             -- String  The string to be measured, surround in quotes if it contains spaces.
::             -- RtnVar  An optional variable to be used to return the string length.
Set "s=#%~1"
Set "len=0"
For %%N in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
  if "!s:~%%N,1!" neq "" (
    set /a "len+=%%N"
    set "s=!s:~%%N!"

Endlocal&if "%~2" neq "" (set %~2=%len%) else echo %len%
Exit /b

What I'm trying to do it get the date modified of the file, and change the format of that date returned to YYYYMMDD. I want the date modified to be appended to the filename. I can have files from multiple days in this folder and each file may have a different date modified date.

Please do not mark this as a duplicate question, because I could not find this approach to doing this here.

I was trying to test for date string length so I can handle dates like 1/1/2019 (length of 8) vs 1/13/2019 (length of 9) vs 10/1/2019 (length of 9) vs 10/22/2019 (length of 10) then using if statements parse the date appropriately with the likes of something like !fdate123:~5,9!!fdate123:~0,1!!fdate123:~2,2! - I have not finished this yet.

I have tried getting the date with dir /T:W testfiles*.* and running a findstr but I don't understand findstr well enough to do that.

I also tried to pull it from forfiles /M BC_Services_Adjustment* /C "cmd /c echo @fdate" and moved on from that as well.

maybe somebody has a better solution, I think mine is a mess right now. Does anybody know how to get the date modified time stamp of every file in a folder, convert it a variable with YYYYMMDD format and then append it into all the files in a folder?

Note: I am not looking for powershell solutions for this question, please do not waste your time posting powershell answers.

Update #2 (5/21/19) I tried magoo's code, I'm still needing a solution to rename the files.

@echo off
pushd "\\server\folder"
SETLOCAL EnableDelayedExpansion

FOR /F "TOKENS=2" %%A IN ('WHERE /T "*.csv"') DO (
     for /f "tokens=1-3delims=/-." %%i in ("%%A") do (
     set "mm=00%%i"&set "dd=00%%j"&set "yy=0000%%k"
     set "fdate123=!yy:~-4!!mm:~-2!!dd:~-2!"
rem echo to test if date modified matches to the right filenames. 
echo !fdate123! ^& %%A
rem ren "%%~nxA" "%%~nxA!fdate123!"

I have tried with the ren "%%~nxA" "%%~nxA!fdate123!" but it's not finding the file. Probably super simple. If somebody can make magoo's code do a rename instead of just echoing the date I can award out the bounty on this question.

Be sure to specify your extentions so if your bat file is in that directory, it will not also be renamed.

@echo off pushd "\\server\path123" SETLOCAL EnableDelayedExpansion FOR /r %%f IN (*.csv, *.txt) DO SET filedatetime=%%~tf & ren "%%~nf.*" "%%~nf!filedatetime:~6,4!!filedatetime:~0,2!!filedatetime:~3,2!%%~xf

Rename files to add date modified to filename with Windows CMD , 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� Hi, Is there a way to take a large group of .pdf files and append the date modified to the end of the file name? So instead of "ABC_abc.pdf" I will get "ABC_abc_01-01-2014.pdf"?

FOR /F "TOKENS=2" %%A IN ('WHERE /T "testfiles*.*"') DO (
 for /f "tokens=1-3delims=/-." %%i in ("%%A") do set "mm=00%%i"&set "dd=00%%j"&set "yy=0000%%k"
 set "fdate123=!mm:~-2!!dd:~-2!!yy:~-4!"
 echo !fdate123!

should allow you to construct the data according to your wishes.

The inner if assigns mm, dd and yy as appropriate, using the delimiters specified analysing %%A as a literal. Each is prefixed by an appropriate number of zeroes. The required string is then constructed using substringing selecting the last 2/4 characters of the string, so an 8-character output is obtained.

I use dd/mm/yyyy format and haven't actually tested this method, but manipulating it to your requirements should be obvious, the only issue really being how to handle yy dates as distingct from yyyy dates, if that's a concern.

Get file modified date & time, We can get file last modified date/time from Windows command line using dir or forfiles commands. dir /T:W filename To get the modified date and time for all files and sub folders in the current directory the 4 comments… add one. To get modified date/time only for files in the current directory(i.e exclude directories from files) dir /T:W /A:-D Using Forfiles command. Using forfiles command we can get modified date and time for all the files in a directory. forfiles /C "cmd /c echo @file @fdate @ftime" We can restrict the command only to certain files using * command.

Yes, I read that you do not want any PowerShell answers. Please be sure not to select this one as the answer. I did not waste my time writing something for you. This is for someone else who might get some benefit.

Param (

$dirlist = @('.') + ($Env:Path.Split(';'))
$extensions = @('') + ($Env:PATHEXT.Split(';'))

$results = foreach ($dir in $dirlist) {
    if (($dir) -and ($dir -ne '')) {
        if (Test-Path -Path $dir -ErrorAction SilentlyContinue) {
            # The directory path exists.
            # Check for presence of the file with any executable extension.
            $dirhash = @{}

            foreach ($extension in $extensions) {
                Get-ChildItem -File -Path $dir -Filter "$CommandName$extension" |
                    ForEach-Object {
                        # If the file name is not already in the hash, add it to the hash
                        # and output it in the pipeline.
                        if (-not $dirhash.ContainsKey($_.Name)) {

$results | ForEach-Object {
    Rename-Item -LiteralPath $_.FullName -NewName ($_.BaseName + $($_.LastWriteTime.ToString('yyyyMMdd')) + $_.Extension)


Now that the OP's intent is known, this is a much more simple problem. Once you are confident the files will be renamed correctly, remove the -WhatIf from the Rename-Item cmdlet.

Set-Location -Path '//server/sharename'

Get-ChildItem -File -Filter 'testfiles*.*' |
    ForEach-Object {
        Rename-Item -LiteralPath $_.FullName -NewName ($_.BaseName + $($_.LastWriteTime.ToString('yyyyMMdd')) + $_.Extension) -WhatIf

How can I append the date and time to a file?, A. You can use the batch file below which will rename a file to REM DateName. CMD REM takes a filename as %1 and renames as %1_YYMMDDHHMM REM 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".

I figured this out on my own, pure batch solution. Takes date modified, appends it to any filename in a directory in YYYYMMDD format. I really was overcomplicating it, can't believe I didn't come up with this prior to setting a bounty. lol

pushd "\\server\folder"
SETLOCAL EnableDelayedExpansion
FOR /r %%f IN (*) DO SET filedatetime=%%~tf & ren "%%~nf.*" "%%~nf!filedatetime:~6,4!!filedatetime:~0,2!!filedatetime:~3,2!%%~xf" 

How to copy a list of file names to text file?, It's very, very easy in the Windows Command-Line Interpreter (all Windows OSes ): available for customizing the normal output of the DIR command; just add the The script could be easily modified to change where the output list file is stored. You can use dir /b > files.txt from the command-line to get the list of filenames� Get date from command line. To print today’s date on the command prompt, we can run date /t. c:\>date /t Thu 05/14/2015 c:\> Just running date without any arguments prints the current date and then prompts to enter a new date if the user wants to reset it. c:\>date The current date is: Sat 05/16/2015 Enter the new date: (mm-dd-yy) c:\>

I believe that the output from robocopy is in a consistent format, so I would suggest this as a possible single line batch-file option:

@PushD "\\server\folder" 2>Nul&&For /F "Tokens=1-4*Delims=/  " %%A In ('RoboCopy . $ testfiles*.* /L /NS /NJS /NJH /NDL /NC /TS')Do @Ren "%%E" "%%A%%B%%C-%%~nxE"

Alternatively, based upon your edited additional example code, this is more likely what you need:

@PushD "\\server\folder" 2>Nul&&For /F "Tokens=1-4*Delims=/  " %%A In ('RoboCopy . $ testfiles*.* /L /NS /NJS /NJH /NDL /NC /TS')Do @Ren "%%E" "testfiles%%A%%B%%C%%~xE"

If each renamed file is run through the for loop again, you may need to expand this from a single line solution to prevent it.

In both code examples, the Delimiters are /TAB                                        

Windows equivalent of the Linux command 'touch'?, (where filename.ext is your file's name). The +,, is a special This works even if the file is not in the current directory (tested on Windows 7). If all you want is to change the file's last modified date (which was my case): This will add a right click context menu for all files with the "Touch File" ability (tested on Windows 7). If your current date time is Nov 02, 2017 15:41:36, then the above example will create a file in the current directory with name “access_20170306-143822.log”. A Sample Batch Script with Date & Time. The complete windows batch script will look like below. To test this create a file test.bat with the following content.

Today’s date as a part of the file name in the batch file 06.06.2016 20.07.2019 Srdjan Stanisic Batch files , Windows Batch files , date variable , using date in file name Using current date as part of the file or a folder (the directory) name is very useful.

Ps.. go to dos prompt and enter Date command and then Time command to see character strings your parsing in the rename command when your building your file name. For Date: Wed 06/08/2005 You start counting from 0 starting with Wed and the add 1 as you move to the right.. The 5th char would be the nbr 6 in this example.

As anyone will tell you, manipulating dates in a batch procedure is nearly impossible. One technique is to use a hybrid script/batch. In this case, I had a sample that uses a one line VBScript to calculate the age of the file using the FOR's ~t argument modifier to deliver the file's DateLastWritten information to the script.

  • shadoe2020, you should have the courtesy of trying the other answers, or at least the ones that fulfilled your request. You should not be updating your question as if completely ignoring my suggested solution.
  • The update says no third party utilities. Does that explain why i cant try it enough? Besides if i wanted robocopy i would have put it in the post. I didnt do that so reasonbly, i ignored that answer.
  • shadoe2020 , I haven't used any third party tools, Robocopy.exe is as much, if not more, a Microsoft product as forfiles.exe. It has been installed as part of Windows Operating Systems since Windows Vista. Prior to that it was available in Windows Resource Kits since Windows NT 4.0. I am absolutely certain that Robocopy.exe will never be defined as a third party tool on a modern Windows computer and that my answer fulfills the criteria you laid out in your questiion.
  • @shadoe2020 - What is driving this requirement that no other executable other than cmd.exe can be used? Is this simply an academic exercise?
  • @lit, there isn't one, the stipulations were, no powershell solutions and, in their update, no third party tools. After noting that the OP had provided their own powershell code in previous questions, I was satisfied that they had a genuine reason to exclude it. My answer however fully complies with both exclusions, it uses an OS supplied Microsoft exectuable, as does their own and Magoo 's answer. I cannot think of any shorter or more efficient code than that in my answer, (which I have today, confirmed as working), and deserve it to be tested with appropriate feedback/credit.
  • This does not search for files in directories on the PATH as is done in the OP's question.
  • And, it will not work correctly in any locale that does not use the en_US date format.
  • All somebody has to do is change the substring syntax for a different locale. Thank you.
  • this renamed a file from 9/18 to the filename of testfiles04082019. I'm not sure this works the way it's supposed to.
  • What was the date shown by where /t for that file?
  • 0408 was the date
  • In that case, how is the batch supposed to work out that it should use 9/18 in this case? Where does the 9/18 come from? where reports 0408.