How to copy directories preserving timestamps in Windows

#!/usr/bin/perl -w
# Touch dirs in a copy of the dir-tree for the mtime to match the original.
# Copyright 2008 Alexander Stcheblikin.

use Cwd;
use Win32API::File::Time qw{:win};      # Optional, see SetFileTime below

# Set your paths here
$src = "D:/src";        # The original directory tree
$dst = "C:/dst";        # A copy which needs directories timestamps fix

sub ScanDirectory {
    my ($workdir) = shift; # Relative to "$src/"!
    my ($startdir) = &cwd; # keep track of where we began
    my $srcworkdir = "$src/$workdir";

    chdir($srcworkdir) or die "Unable to enter dir $srcworkdir: $!\n";

    my @names = ();
    if (opendir(DIR, ".")) {
        @names = readdir(DIR);
    else {
         warn "Unable to open $workdir: $!\n";
         # a warning is enough:
         # don't let some minor permissions problems stop the whole gig.

    foreach my $name (@names){
        next if ($name eq ".");
        next if ($name eq "..");

        if (-d $name){
    my ($atime, $mtime) = (stat("."))[8..9];    # used in utime() call
    chdir($startdir) or die "Unable to change to dir $startdir:$!\n";
    # We've done with the $workdir, it's safe now to re-touch the
    # dst equivalent of it.
    #utime($atime, $mtime, "$dst/$workdir")
    #   or warn "Unable to re-touch $workdir: $!\n";

    # An alternative using Win32API::File::Time
    # What's it good for: set the "Time Created"
    # - not found in UNIX-style utime
    SetFileTime ("$dst/$workdir", GetFileTime("$srcworkdir"));
    # Note:
    # Comment "SetFileTime()" and uncomment "utime()" above
    # if you cannot (or don't want) to use Win32API::File::Time

chdir($src) or die "Unable to enter src dir $src: $!\n";

1 Star2 Stars3 Stars4 Stars5 Stars

One thought on “How to copy directories preserving timestamps in Windows

  1. Hi,
    As this post appeared in the first page on a Google search about Robocopy and WinRAR, I feel the need to add that Robocopy (since version 26, which I read came with Windows Vista) can perfectly copy directories with all timestamps. It can even correct the timestamps without having to re-copy the actual files, which was a “life-saver” for me once, when some program added one file to every single subdirectory of my main hard drive, thus changing their modified date to the current date, which was definitely an issue as I use folders’ timestamps a lot for sorting purposes — fortunately I had a backup and Robocopy solved this little nightmare in just a few seconds.

    The switch to copy directory timestamps is :

    (There’s also /TIMFIX which is described in the integrated /? help as “Fix file TIMes on all files, even skipped ones.)

Leave a Reply

Your email address will not be published.