How to get last modified date on Windows command line for a set of files?
Asked Answered
A

10

32

I have been using the following command to get the file date. However, the fileDate variable has been returning blank value ever since we moved to a different server (Windows Server 2003).

FOR /f %%a in ('dir myfile.txt^|find /i " myfile.txt"') DO SET fileDate=%%a 

Is there any other more reliable way to get the file date?

Aphonia answered 21/1, 2010 at 17:24 Comment(0)
D
46

In the code that follows, change % to %% for use in batch file, for %~ta syntax enter call /?

for %a in (MyFile.txt) do set FileDate=%~ta

Sample output:

for %a in (MyFile.txt) do set FileDate=%~ta
set FileDate=05/05/2020 09:47 AM

for %a in (file_not_exist_file.txt) do set FileDate=%~ta
set FileDate=
Dynamometry answered 22/1, 2010 at 10:1 Comment(6)
+1. That's actually the correct one. Parsing the output of dir is insanity at best. Side note: In a batch file, double the % signs.Banjo
Thanks, one more question: how get just the date portion. Is the following syntax reliable enough or is there a better way. set FileDate=%FileDate:~0,10%Aphonia
It may not work if you change your international settings, but otherwise it should be OKDynamometry
can you give me a hint as to what is actually happening here? I'm not sure I understand what %~ta or %a isHusband
For me no matter what I do, the result is blank. Default english US.Charis
@MarkDeven, if you're not getting a result then either the file you're specifying doesn't exist or you current login doesn't have access to it.Stupefaction
F
27

Useful reference to get file properties using a batch file, included is the last modified time:

FOR %%? IN ("C:\somefile\path\file.txt") DO (
    ECHO File Name Only       : %%~n?
    ECHO File Extension       : %%~x?
    ECHO Name in 8.3 notation : %%~sn?
    ECHO File Attributes      : %%~a?
    ECHO Located on Drive     : %%~d?
    ECHO File Size            : %%~z?
    ECHO Last-Modified Date   : %%~t?
    ECHO Drive and Path       : %%~dp?
    ECHO Drive                : %%~d?
    ECHO Fully Qualified Path : %%~f?
    ECHO FQP in 8.3 notation  : %%~sf?
    ECHO Location in the PATH : %%~dp$PATH:?
)
Flinger answered 30/1, 2018 at 10:52 Comment(1)
how to use or implement this?Musil
S
21

You can do it

forfiles /M myfile.txt /C "cmd /c echo @fdate @ftime"
Spooky answered 12/5, 2015 at 16:5 Comment(6)
is this locale dependent?Charis
Cool, didn't know there is forfiles - quite more intuitive than all the cryptic for examples on the net.Salvation
this includes seconds, where ~t is only precise to the minute. Powershell also gives seconds via the two part command: $myFileInfo = Get-Item C:\myPath\myFile.txt $myFileInfo.LastWriteTimeOrdnance
Hmm...how to set/get those date variables in a batch-file?Gimel
@BeatriceThalo You can one-line it by just wrapping the first part: (get-item filePath.txt).LastWriteTimeHeroics
The string format for this command varies depending on the system date/time format preferences (control panel -> region -> change date/time number formats). It's not reliable if you want to parse the output.Excitant
L
8

To get the last modification date/time of a file in a locale-independent manner you could use the wmic command with the DataFile alias:

wmic DataFile where "Name='D:\\Path\\To\\myfile.txt'" get LastModified /VALUE

Regard that the full path to the file must be provided and that all path separators (backslashes \) must be doubled herein.

This returns a standardised date/time value like this (meaning 12th of August 2019, 13:00:00, UTC + 120'):

LastModified=20190812130000.000000+120

To capture the date/time value use for /F, then you can assign it to a variable using set:

for /F "delims=" %%I in ('
    wmic DataFile where "Name='D:\\Path\\To\\myfile.txt'" get LastModified /VALUE
') do for /F "tokens=1* delims==" %%J in ("%%I") do set "DateTime=%%K"

The second for /F loop avoids artefacts (like orphaned carriage-return characters) from conversion of the Unicode output of wmic to ASCII/ANSI text by the first for /F loop (see also this answer).

You can then use sub-string expansion to extract the pure date or the time from this:

set "DateOnly=%DateTime:~0,8%"
set "TimeOnly=%DateTime:~8,6%"

To get the creation date/time or the last access date/time, just replace the property LastModified by CreationDate or LastAccessed, respectively. To get information about a directory rather than a file, use the alias FSDir instead of DataFile.

For specifying file (or directory) paths/names containing both , and ), which are usually not accepted by wmic, take a look at this question.

Check out also this post as well as this one about how to get file and directory date/time stamps.

Lorimer answered 12/8, 2019 at 11:15 Comment(7)
precision in microseconds (aka .001 milliseconds)Ordnance
Note that this is deprecated and is expected to be removed. research.nccgroup.com/2022/03/10/…Peisch
Yes, @Nelson; an up-to-date alternative is to leverage from PowerShell: PowerShell -NoProfile -NoLogo -Command "(Get-Item 'D:\Path\To\myfile.txt').LastWriteTime | Get-Date -Format o" (of course also with .CreationTime or .LastAccessTime)…Lorimer
@Lorimer is this also locale independent format or what should one write to make it locale independent? I'm getting an error at %%I saying "%%I was unexpected at this time." for the solution that was posted - plus if it's deprecated I would go with the powershell cmd to spare myself from suffering later. I'm getting back the following for the PS cmd: "2023-04-25T00:31:11.6539686+03:00"Lithophyte
okay, actually i just found that you can set the format to suit your need, thanksLithophyte
@RandomDude, the used command wmic is meanwhile deprecated, so PowerShell is a good option to retrieve locale-independent date/time information. Concerning the %%I error: have you executed the command line in a Command Prompt rather than in a batch file? if so, use %I instead of %%I (same for other loop variables, of course)…Lorimer
@Lorimer I had this in batch file, I also read somewhere what you just mentioned. I just didn't realize, that I can change the date format in the command at first, so I wasn't sure that the response I get back for the PS command is locale-independent. I needed this for folder generation, I wanted to generate folder names with the timestamp in it, and luckily this PS cmd with the formatting was exactly what I was looking for, thanks.Lithophyte
D
2

It works for me on Vista. Some things to try:

  1. Replace find with the fully-qualified path of the find command. find is a common tool name. There's a unix find that is very differet from the Windows built-in find. like this:
    FOR /f %%a in ('dir ^|%windir%\system32\find.exe /i "myfile.txt"') DO SET fileDate=%%a

  2. examine the output of the command in a cmd.exe window. To do that, You need to replace the %% with %.
    FOR /f %a in ('dir ^|c:\windows\system32\find.exe /i "myfile.txt"') DO SET fileDate=%a
    That may give you some ideas.

  3. If that shows up as blank, then again, at a command prompt, try this:

    dir | c:\windows\system32\find.exe /i "myfile.txt"

This should show you what you need to see.

If you still can't figure it out from that, edit your post to include what you see from these commands and someone will help you.

Deed answered 21/1, 2010 at 17:38 Comment(4)
my statetement and (the step 1 and 2) work on my computer and any other win server 2003 that I can get my hand on. could this be an issue where it run under service id and trigger by a scheduler?Aphonia
yes it could be. The find program may be different for a different service ID, because it has a different path. Best to run these commands under the service ID to capture and examine the output.Deed
Some years ago we had some similar issues regarding the batch processing of the output of the DIR command, because of different language of the command processor (in our case, our batch file worked in win2000 english and spanish, but failed in german).Viridian
Also can happen with UK versus US english!Deed
B
2

You could try the 'Last Written' time options associated with the DIR command

/T:C -- Creation Time and Date
/T:A -- Last Access Time and Date
/T:W -- Last Written Time and Date (default)

DIR /T:W myfile.txt

The output from the above command will produce a variety of additional details you probably wont need, so you could incorporate two FINDSTR commands to remove blank lines, plus any references to 'Volume', 'Directory' and 'bytes':

DIR /T:W myfile.txt | FINDSTR /v "^$" | FINDSTR /v /c:"Volume" /c:"Directory" /c:"bytes"

Attempts to incorporate the blank line target (/c:"^$" or "^$") within a single FINDSTR command fail to remove the blank lines (or produce other errors) when the results are output to a text file.

This is a cleaner command:

DIR /T:W myfile.txt | FINDSTR /c:"/"
Barret answered 17/10, 2020 at 8:3 Comment(0)
O
1

you can get a files modified date using vbscript too

Set objFS=CreateObject("Scripting.FileSystemObject")
Set objArgs = WScript.Arguments
strFile= objArgs(0)
WScript.Echo objFS.GetFile(strFile).DateLastModified

save the above as mygetdate.vbs and on command line

c:\test> cscript //nologo mygetdate.vbs myfile
Obstetrician answered 22/1, 2010 at 0:33 Comment(2)
is this locale dependent?Charis
@MarkDeven, this is locale-independent as here a real date/time data type is involved...Lorimer
D
1

If you're able to bring in an EXE, I recommend gdate.exe (from GNU CoreUtils for Windows). It can give the current date or the date of a file, in many different formats, and customizable. I use it to get the last modified date-time of files that I can compare without any parsing (ie. local-independent), using the %s (seconds since the epoch), optionally with %N to get nano-second precision.

Some examples:

C:\>dir MyFile.txt
02/10/2021  10:54 PM                 4 MyFile.txt

C:\>gdate -r MyFile.txt +%Y-%m-%d
2021-02-10

C:\>gdate -r MyFile.txt "+%Y-%m-%d %H:%M:%S"
2021-02-10 22:54:50

C:\>gdate -r MyFile.txt +%s
1613015690

C:\>gdate -r MyFile.txt +%s.%N
1613015690.093962600
Deibel answered 11/2, 2021 at 4:0 Comment(0)
A
0

What output (exactly) does dir myfile.txt give in the current directory? What happens if you set the delimiters?

FOR /f "tokens=1,2* delims= " %%a in ('dir myfile.txt^|find /i " myfile.txt"') DO SET fileDate=%%a 

(note the space after delims=)
(to make life easier, you can do this from the command line by replacing %%a with %a)

Agnesse answered 21/1, 2010 at 17:51 Comment(0)
J
0

Using PowerShell to get a specific date format:

for /f "usebackq" %d in (`powershell "(get-item \"Rar.exe\").lastWriteTime.toString(\"yyyy-MM-dd\")"`) do ( echo ren "Rar.exe" "%d_rar550.exe" )
rem
Juanajuanita answered 10/9, 2022 at 20:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.