Feb 19 2011
I recently transferred a few thousand files, totalling gigabytes, from one computer to another over a slowish internet connection. At the end of the transfer, I realized the process I used had lost all the original file timestamps. Rather, all the files on the destination machine had a create/modify date of when the transfer occurred. In this particular case I had uploaded files to Amazon S3 from end then downloaded them from another, but there are numerous other ways to transfer files that lose the timestamps; for example, many FTP clients do so by default.
This file transfer took many hours, so I wasn’t inclined to delete and try again with a better (timestamp-preserving) transfer process. Rather, it shouldn’t be very hard to fix them in-place.
Both machines were Windows servers; neither had a broad set of Unix tools installed. If I had those present, the most obvious solution would be a simple rsync command, which would fix the timestamps without retransferring the data. But without those tools present, and with an unrelated desire to keep these machines as “clean” as possible, plus a firewall obstacle to SSH, I looked elsewhere for a fix.
I did, however, happen to have a partial set of Unix tools (in the form of the MSYS tools that come with MSYSGIT) on the source machine. After a few minutes of puzzling, I came up with this approach:
- Run a command on the source machine
- … which looks up the timestamp of each file
- … and stores those in the form of batch file
- Then copy this batch file to the destination machine and run it.
Here is the source machine command, executed at the top of the file tree to be fixed:
find . -print0 | xargs -0 stat -t "%d-%m-%Y %T" -f 'nircmd.exe setfilefoldertime "%N" "%Sc" "%Sm"' | tr '/' '\\' >~/fix_dates.bat
I broken it up to several lines here, but it’s intended as one long command.
- “find” gets the names of every file and directory in the file tree
- xargs feeds these to the stat command
- stat gets the create and modify dates of each file/directory, and formats the results in a very configurable way
- tr converts the Unix-style “/” paths to Windows-style “\” paths.
- The results are redirected to (stored in) a batch file.
As far as I can tell, the traditional set of Windows built in command line tools does not include a way to set a file or directory’s timestamps. I haven’t spent much time with Powershell yet, so I used the (very helpful) NIRCMD command line utilities, specifically the setfilefoldertime subcommand. The batch file generated by the above process is simply a very long list of lines like this:
nircmd.exe setfilefoldertime "path\filename" "19-01-2000 04:50:26" "19-01-2000 04:50:26"
I copied this batch file to the destination machine and executed it; it corrected the timestamps, the problem was solved.
If you found this post useful, please link to it from your web site, mention it online, or mention it to a colleague.
3 responses so far